Jef*_*_Hd 5 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
Run Code Online (Sandbox Code Playgroud)
结果是:
'RankingInline.fields' refers to field 'account_type' that is missing from the form.
Run Code Online (Sandbox Code Playgroud)
我也尝试过使用 model__field 方法,我将其用作:
fields = ('product', 'product__account_type', 'rank')
Run Code Online (Sandbox Code Playgroud)
结果是:
'RankingInline.fields' refers to field 'product__account_type' that is missing from the form.
Run Code Online (Sandbox Code Playgroud)
模型定义如下:
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)
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
我认为您正在寻找的是嵌套内联,因为您想在 RankingInline 中将“产品”扩展为内联。目前 Django 没有内置这样的功能。这个问题是相关的:Nested inlines in the Django admin?
您还可以查看Django DOC 中的“使用多对多中间模型”部分。那可能有用。
实际上,除了内联产品字段条目之外,Django 还会向您显示一个绿色的小“+”按钮,您可以使用它来创建新产品以分配给 BestBuy 的当前条目。这可能是您使用的替代方法。
| 归档时间: |
|
| 查看次数: |
10318 次 |
| 最近记录: |