5

我正在尝试访问 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)

我究竟做错了什么?

4

3 回答 3

6

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

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

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

于 2012-11-13T22:51:26.463 回答
0

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

readonly_fields = ('product', 'rank', 'account_type')
于 2014-01-28T18:38:48.213 回答
0

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

于 2012-11-13T08:15:48.557 回答