我有一个独特的问题,它应该在 django admin 中处理。
我有以下模型结构...
class Product(models.Model):
name = models.CharField(max_length = 100)
base_price = models.DecimalField(max_digits = 5, decimal_places = 2)
def __unicode__(self):
return self.name
class Country(models.Model):
name = models.CharField(max_length = 2)
base_price = models.DecimalField(max_digits = 5, decimal_places = 2)
def __unicode__(self):
return self.name
class CountryProduct(models.Model):
country = models.ForeignKey(Country)
product = models.ForeignKey(Product)
overriden_price = models.DecimalField(max_digits = 5, decimal_places = 2)
class Meta:
unique_together = (("country", "product"),)
如此处所示,产品与国家/地区之间存在多对多关系...。我想提供管理界面来覆盖给定国家/地区和产品的基本价格。
具有如下 ui 的选项,此处破折号 (-) 代表默认价格,数字中的值代表给定国家和产品的替代价格。
countries -> | US | UK
products | |
---------------------------
Product1 | - | 10
Product2 | 5 | 7
但我不知道该怎么做......
我愿意考虑替代方法(包括模型结构的更改),只要它满足要求...您的任何输入都对我有用...
提前致谢:)
最佳答案
我得到了解决方案,这是我对我的问题的回答......让我与你分享......我按照以下方式更改了模型......
class Product(models.Model):
name = models.CharField(max_length = 100)
base_price = models.DecimalField(max_digits = 5, decimal_places = 2)
def __unicode__(self):
return self.name
class Country(models.Model):
name = models.CharField(max_length = 2)
base_price = models.DecimalField(max_digits = 5, decimal_places = 2)
products = models.ManyToManyField(Product, through = 'CountryProduct')
def __unicode__(self):
return self.name
class CountryProduct(models.Model):
country = models.ForeignKey(Country)
product = models.ForeignKey(Product)
overriden_price = models.DecimalField(max_digits = 5, decimal_places = 2)
class Meta:
unique_together = (("country", "product"),)
class CountryProductInline(admin.TabularInline):
model = CountryProduct
class CountryAdmin(admin.ModelAdmin):
inlines = [CountryProductInline]
class ProductAdmin(admin.ModelAdmin):
inlines = [CountryProductInline]
虽然这不是我预期的方式,但这给了我更好的解决方案....
关于python - 在 django admin 中表示多对多关系的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2332238/