django - 从管理表格内联访问外键字段

标签 django django-models django-admin

我正在尝试访问 Django 管理中的表格内联内的外键字段。

尽管我尽了最大努力,但似乎仍无法使其发挥作用。我当前的代码是:

class RankingInline(admin.TabularInline):
    model = BestBuy.products.through
    fields = ('product', 'account_type', 'rank')
    readonly_fields = ('product', 'rank')
    ordering = ('rank',)
    extra = 0

    def account_type(self, obj):
        return obj.products.account_type

结果是:

'RankingInline.fields' refers to field 'account_type' that is missing from the form.

我还尝试使用 model__field 方法,我将其用作:

fields = ('product', 'product__account_type', 'rank')

结果是:

'RankingInline.fields' refers to field 'product__account_type' that is missing from the form.

模型定义如下:

class Product(BaseModel):  
    account_type = models.CharField(choices=ACCOUNT_TYPE_OPTIONS, verbose_name='Account Type', max_length=1, default='P')

class Ranking(models.Model):
    product = models.ForeignKey(Product)
    bestbuy = models.ForeignKey(BestBuy)
    rank = models.IntegerField(null=True, blank = True)

class BestBuy(BaseModel):
    products = models.ManyToManyField(Product, through='Ranking')

class BaseModel(models.Model):
    title = models.CharField(max_length = TODO_LENGTH)
    slug = models.CharField(max_length = TODO_LENGTH, help_text = """The slug is a url encoded version of your title and is used to create the web address""")

    created_date = models.DateTimeField(auto_now_add = True)
    last_updated = models.DateTimeField(auto_now = True)

我做错了什么?

最佳答案

我认为您正在寻找的是嵌套内联,因为您想将“Product”扩展为 RankingInline 中的内联。目前Django没有内置这样的功能。这个问题是相关的:Nested inlines in the Django admin?

您还可以查看Django DOC中的“使用多对多中间模型”部分。 。这可能有用。

实际上,除了内联产品字段条目之外,Django 还会向您显示一个小的绿色“+”按钮,您可以使用该按钮创建一个新产品以分配给您当前的 BestBuy 条目。这可能是您可以使用的替代方案。

关于django - 从管理表格内联访问外键字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13290460/

相关文章:

Django - ModelForm 创建还是更新?

django - django admin-如何显示缩略图而不是文件路径

django - 如何让 grappelli 自动完成小部件代替 ModelMultipleChoiceField(在一对多方向上)工作?

django - 如何将 imagekit 与 S3 集成

django - 如何在 Django 中配置 X-Frame-Options 以允许 iframe 嵌入一个 View ?

python - 如何在 Django Python 中使用检测意图(文本)?

python - RuntimeError : 'list' must be None or a list, not <class 'str' > while trying to start celery worker

python - 我如何使用Django查询集过滤器创建views.py来比较django中两个不同表的特定值?

python - 管理站点自动获取当前用户

django.db.utils.ProgrammingError : Table doesn't exist