How to access ManyToManyField between two applications using ContentTypes for Django admin?

Let's say I have this application called Pantry, which should connect to any other application with which I can come. To unleash an application, a shared relationship is used through the LinkedItem model, which connects the Ingredients model to applications outside the pantry.

I can create filter_horizontal for the LinkedItem admin in Django. Now I would like the content at the other end of the generic relationship, for example, an application called Bakery, to be able to do filter_horizontal with the ingredients.

pantry models.py

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import fields

class Ingredient(models.Model):
   '''
   Model containing all the ingredients, their slugs, and their descriptions
   '''
   name = models.CharField(unique=True, max_length=100)
   slug = models.SlugField(unique=True, max_length=100)
   description = models.CharField(max_length=300)

   # method to return the name of the db entry
   def __str__(self):
      return self.name

class LinkedItem(models.Model):
   '''
   Model that links ingredients to various other content models
   '''
   content_type = models.ForeignKey(ContentType)
   object_id = models.PositiveIntegerField()
   content_object = fields.GenericForeignKey('content_type', 'object_id')

   ingredient = models.ManyToManyField(Ingredient)

   # method to return the name of the db entry
   def __str__(self):
      return self.ingredient.name

   # defines options for the model itself
   class Meta:
     unique_together = (('content_type','object_id'))    # prevents duplicates

Bakery admin.py

from django.contrib import admin
from bakery.models import Cake

class CakeAdmin(admin.ModelAdmin):
   filter_horizontal = ('') # what to put here so ingredients show up?

Any ideas?

+4
1

, GenericTabularInline LinkedItem , , :

from django.contrib.contenttypes.admin import GenericTabularInline

class LinkedItemAdmin(GenericTabularInline):
    model = LinkedItem

    # choosing the field and display
    field = ['ingredient']
    filter_horizontal = ['ingredient']

    # These help with removing some potential issues in the admin
    extra = 0
    min_num = 1
    max_num = 1
    can_delete = False

CakeAdmin , .

class CakeAdmin(admin.ModelAdmin):
    inlines = [LinkedItemAdmin]
+1

Source: https://habr.com/ru/post/1626477/


All Articles