gpt4 book ai didi

python - 如何在Django admin中使用ContentTypes的两个应用程序之间的ForeignKey上使用filter_horizo​​ntal?

转载 作者:行者123 更新时间:2023-12-03 21:36:42 27 4
gpt4 key购买 nike

假设我有一个名为 Pantry 的应用程序,它可以连接到我可能遇到的任何其他应用程序。为了保持应用程序解耦,通过模型 LinkedItem 使用通用关系,该模型将成分模型连接到 Pantry 外部的应用程序。

我希望通用关系另一端的内容,比如名为 Bakery 的应用程序,能够对成分进行 filter_horizo​​ntal。

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

面包店
管理文件
from django.contrib import admin
from bakery.models import Cake

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

有任何想法吗?

最佳答案

我想这就是 GenericRelation 是为了,所以您需要在 Cake 中添加一个模型并在您的 CakeAdmin 中使用它的名称。

但是,如果您不想像 M2M fields are not supported for relations with intermediary models 那样做很多变通方法,则需要使用内联。 .

关于python - 如何在Django admin中使用ContentTypes的两个应用程序之间的ForeignKey上使用filter_horizo​​ntal?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35078439/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com