如何在使用Django admin中的ContentTypes在两个应用程序之间的ForeignKey上使用filter_horizontal?

2024-03-28 14:03:11 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个名为Pantry的应用程序,它可以连接到我可能附带的任何其他应用程序。为了保持应用程序的解耦,通过模型LinkedItem使用泛型关系,LinkedItem将配料模型与配餐间外的应用程序连接起来。在

我希望在通用关系的另一端的内容,比如一个名为Bakery的应用程序,能够对成分进行水平过滤。在

餐具室在模型.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.ForeignKey(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

面包店在管理员py

^{pr2}$

有什么想法吗?在


Tags: thedjangonamefrom模型importself应用程序