我有以下代码:
class Item(models.Model):
name = models.CharField(max_length=100)
keywords = models.CharField(max_length=255)
type = models.ForeignKey(Type)
class Meta:
abstract = True
class Variant(models.Model):
test_field = models.CharField(max_length=255)
class Product(Item):
price = models.DecimalField(decimal_places=2, max_digits=8,null=True, blank=True)
brand = models.ForeignKey(Brand)
variant = models.ForeignKey(Variant)
def get_fields(self):
return [(field.name, field.value_to_string(self)) for field in Product._meta.fields]
def __unicode__(self):
return self.name
我正在使用 Grappelli。 我希望我的产品有多种变体。我应该使用manytomanyfield吗?
我希望能够直接在管理中向我的产品添加变体。现在我得到一个空的下拉列表,没有变体(因为它们不存在)。
我以为当你指定外键时 Django 会自动执行此操作?
如何让变体字段直接显示在编辑中的产品页面上? 我读过一些有关管理中内联字段的内容?
最佳答案
嗯,情况正好相反:)
1/将外键字段放在您的 Variant 中,而不是您的 Product 中(您描述的实际上是 OneToMany 关系)。
2/在 admin.py 的相关 ProductAdmin 中将变体作为内联链接到您的产品(即 VariantInline)。
有关更多信息,请参阅文档:https://docs.djangoproject.com/en/1.6/ref/contrib/admin/#inlinemodeladmin-objects
希望这有帮助!
问候,
关于python - Django一对多,在Admin中动态添加字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21731675/