从Admin Tabular Inline访问外键字段

时间:2012-11-08 14:01:55

标签: django django-models django-admin

我正在尝试访问Django Admin中Tabular Inline中的外键字段。

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

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)

我做错了什么?

3 个答案:

答案 0 :(得分:4)

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

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

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

您只需将method-field添加到readonly_fields:

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