【问题标题】:Access foreign key fields from Admin Tabular Inline从 Admin Tabular Inline 访问外键字段
【发布时间】:2012-10-28 17:35:54
【问题描述】:

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

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

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)

我做错了什么?

【问题讨论】:

    标签: django django-models django-admin


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      您的新字段account_type 应在ModelAdmin(即RankingAdmin)中定义,而不是在TabularInline(即RankingInline)中。它只能从 TabularInline 访问。

      【讨论】:

        【解决方案3】:

        您只需将方法字段添加到 readonly_fields:

        readonly_fields = ('product', 'rank', 'account_type')
        

        【讨论】:

          猜你喜欢
          • 2013-06-08
          • 2018-04-25
          • 2020-01-26
          • 2012-03-14
          • 2018-03-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-08-23
          相关资源
          最近更新 更多