如何在Django中正确使用auto_created属性? [英] How to correctly use auto_created attribute in django?
问题描述
我需要创建自己的中间模型.
I need to create my own intermediate model.
class class1(models.Model)
class class2(models.Model):
field1 = models.ManyToManyField(class1, through="class3")
class class3(models.Model):
field1 = models.ForeignKey(class1)
field2 = models.ForeignKey(class2)
field3 = models.IntegerField()
class Meta:
auto_created = True
我使用"auto_created = True",因为在以下代码中,我出现了错误:
I use "auto_created=True" because in the following code, I had the error :
AttributeError:无法在用于指定中介模型的ManyToManyField上使用add().
AttributeError: Cannot use add() on a ManyToManyField which specifies an intermediary model.
for m2m_field in self._meta.many_to_many:
for m2m_link in getattr(self, m2m_field.get_attname()).all():
getattr(to_object, m2m_field.get_attname()).add(m2m_link)
现在它可以正常工作,但是当我尝试进行makemigration时,django希望删除我的class3(中间类),并删除class2中field1中的通过"属性.
Now it works fine, but when I try to do a makemigration, django wants to remove my class3 (the intermediate class), and removing the "through" attribute in the field1 in class2.
我做错了什么?有解决方案吗?
What am I doing wrong ? Any solutions ?
全部.
推荐答案
据我所知,Meta
类中的auto_created
属性是未记录的,因此应避免使用它.
As far as I am aware, the auto_created
attribute in the Meta
class is undocumented, so you should avoid using it.
正如AttributeError
所说,不可能将add()
用于使用中介模型的多对多字段.正确的解决方法是创建中间模型的实例,而不是使用add()
.
As the AttributeError
says, it is not possible to use add()
for a many to many field that uses an intermediary model. The correct fix is to create an instance of the intermediate model, instead of using add()
.
class3.objects.create(field_1=c1, field_2=c2, field_3=1).
See the docs on extra fields in many to many relationships for more info.
这篇关于如何在Django中正确使用auto_created属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!