python - 在 django admin 中表示多对多关系的更好方法

标签 python django django-models django-admin

我有一个独特的问题,它应该在 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/

相关文章:

python - uWSGI 运行错误的 Python 版本

Django 将请求数据传递给 Forms.py

python - 如何在 Django 中访问通过表单集上传的图像?

python - 无法使用_set查询外键相关对象| Django ?

python - VPython 脚本的输出是什么?为什么我会在 Chrome 中打开它?

python - 相互依赖的模块

python - 在 Python 中将元组转换为整数

python - 通过不同的分组列快速过滤 Pandas DataFrame 的方法?

python - Django 防止远程数据库迁移

python - Django 查询查找具有大于零的特定值的行数,按用户分组