简体   繁体   English

如何避免django“与相关的m2m字段冲突”错误?

[英]How to avoid django “clashes with related m2m field” error?

I have a lot of models with voting functionality, so I created a structure like this: 我有很多具有投票功能的模型,所以我创建了一个这样的结构:

class Voteable(models.Model):
    likes_balance = models.IntegerField(default=0, editable=False)
    votes = models.ManyToManyField(User, blank=True, editable=False)
    likes = models.ManyToManyField(User, blank=True, editable=False)

    class Meta:
        abstract = True

class Item(Voteable):
    title = models.CharField(max_length=20, db_index=True)
    description = models.TextField(max_length=1000)
    contact_user = models.ForeignKey(User, null=True, blank=True)

    class Meta:
        abstract = True

class Movie(Item):
    cover = models.ImageField(upload_to='images/covers/')

class Car(Item):
    seller = models.CharField(max_length=50)

When I try to create tables with "python manage.py syncdb" I get error message: 当我尝试使用“python manage.py syncdb”创建表时,我收到错误消息:

Accessor for m2m field 'likes' clashes with related field 'User.movie_set'. m2m字段的访问者'喜欢'与相关字段'User.movi​​e_set'的冲突。 Add a related_name argument to the definition for 'likes'. 将related_name参数添加到“likes”的定义中。

Of cause I have much more fields in Item class, so don't want to copy all of them to all subclasses and just set related_name like suggested in error. 因为我在Item类中有更多的字段,所以不想将它们全部复制到所有子类,只是设置像错误建议的related_name。

Any suggestions how to deal with it? 有什么建议怎么处理吗?

I found a solution in Django documention . 我在Django文档中找到了一个解决方案

It's possible to write in abstract models things like this: related_name="%(app_label)s_%(class)s_related" 可以在抽象模型中编写如下内容: related_name="%(app_label)s_%(class)s_related"

Normally if you add a related_name as suggested in your M2M definition, it should work : 通常,如果您按照M2M定义中的建议添加related_name,它应该工作:

class Voteable(models.Model):
    likes_balance = models.IntegerField(default=0, editable=False)
    votes = models.ManyToManyField(User, blank=True, editable=False, related_name='votes')
    likes = models.ManyToManyField(User, blank=True, editable=False, related_name='likes')

    class Meta:
        abstract = True

It's because by not doing so, Django will add two user_id in the Voteable table, resulting in a clash because there is twice the same column name. 这是因为如果不这样做,Django会在Voteable表中添加两个user_id,导致冲突,因为列名相同。 Adding a related_name force Django to use the given related_name instead of the {Foreign Table Name}_id column name. 添加related_name强制Django使用给定的related_name而不是{Foreign Table Name} _id列名。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM