【问题标题】:django "is a manually-defined m2m relation through model...which does not have foreign keys to"django“是通过模型手动定义的m2m关系......它没有外键”
【发布时间】:2013-08-17 06:09:28
【问题描述】:

在这方面有一些接近的,但我能找到的只是我正在做的事情,但它不起作用。

这是一个示例:您的产品可以有多个选项。每个选项可以有多个选择。

class Option_Choices(models.Model):
    """
    choices for each option
    """
    name = models.CharField(max_length=30)

    def __unicode__(self):
        return self.name


class Product_Options(models.Model):
    """
    products can have many options
    """
    name = models.CharField(max_length=30)
    option_type = models.IntegerField(choices=OPTION_TYPE)
    choices = models.ManyToManyField(Option_Choices, related_name='product_options_choices')

    def __unicode__(self):
        return self.name


class Product(models.Model):
    """
    there are options for products - different sizes / colors
    """
    name = models.CharField(max_length=30)
    options = models.ManyToManyField(Product_Options, related_name='product_options')

    def __unicode__(self):
        return self.name

看起来很简单,我得到了这个错误

'options'是通过模型手动定义的m2m关系 Product_Options,它没有 Product_Options 的外键 和产品

我尝试了很多不同的方法,包括使用“通过”无法弄清楚为什么这不起作用。这是每个人都说要做的。有什么想法吗?

【问题讨论】:

    标签: django python-3.x m2m


    【解决方案1】:

    我通常将 m2m 定义颠倒如下。在上面的代码中,由于模型类名称中的下划线,您会看到表名冲突。如果您删除下划线,它应该可以工作。

    如果您想保留下划线,则可以颠倒关系。

    class Option_Choices(models.Model):
        """
        choices for each option
        """
        name = models.CharField(max_length=30)
        product_options = models.ManyToManyField("Product_Options", related_name='choices')
    
    
    class Product_Options(models.Model):
        """
        products can have many options
        """
        OPTION_TYPE=(
            ('Color', 1),
        )
        name = models.CharField(max_length=30)
        option_type = models.IntegerField(choices=OPTION_TYPE)
        products = models.ManyToManyField("Product", related_name='options')
    
    
    class Product(models.Model):
        """
        there are options for products - different sizes / colors
        """
        name = models.CharField(max_length=30)
    

    【讨论】:

    • “反转”M2M 关系是错误的。见the docs
    • @hobs 你能详细说明一下吗?
    • 我误解了你所说的“反向”是什么意思。我认为您通过将 FK 字段放在相反的表中来反转关系的方向,并且我没有向右滚动足够远以看到您没有将 Option_Choices 定义为显式的 through 模型。不能将 M2M 放在直通表中……但你没有,所以你没事。这就是我通过略读得到的。
    猜你喜欢
    • 1970-01-01
    • 2010-10-23
    • 2016-05-07
    • 1970-01-01
    • 2015-06-03
    • 1970-01-01
    • 2015-08-01
    • 1970-01-01
    • 2017-05-14
    相关资源
    最近更新 更多