“已经存在”错误
class Product(models.Model):
name = models.CharField(verbose_name="Name", max_length=255, null=True, blank=True)
the_products_inside_combo = models.ManyToManyField('self', verbose_name="Products Inside Combo", help_text="Only for Combo Products", blank=True)
不过,我得到这个错误,当我试图把重复的值:“已经存在”错误
与此From_product-to_product关系,从产品和到 产品已经存在。
每对(Product, Product)
必须是唯一的。这就是为什么你会得到already exists
错误。
在幕后,Django的创建一个中介连接表 代表了许多一对多的关系。
你想要做什么做的是有很多一对多两种模型之间的关系(不要介意,他们是相同的)与存储更多的信息 - 的数量(所以你必须ProductA = 2x ProductB + ...
在为了模拟这种关系,你必须创建中介模型,并用through
选项文档解释了它非常好,所以来看看。
https://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany
更新
这里是最小的工作例如:
class Product(models.Model):
name = models.CharField(verbose_name='Name', max_length=255, null=True, blank=True)
products = models.ManyToManyField('self', through='ProductGroup', symmetrical=False)
def __str__(self):
return self.name
class ProductGroup(models.Model):
parent = models.ForeignKey('Product', related_name='+')
child = models.ForeignKey('Product', related_name='+')
和管理模式:
class ProductGroupInline(admin.TabularInline):
model = Product.products.through
fk_name = 'parent'
class ProductAdmin(admin.ModelAdmin):
inlines = [
ProductGroupInline,
]
admin.site.register(Product, ProductAdmin)
admin.site.register(ProductGroup)
正如你所看到的递归Product
- Product
关系进行建模与ProductGroup
(through
参数)。几条注释:
带中间表的多对多字段不能是对称的,因此
symmetrical=False
。 Details。为
ProductGroup
反向存取被禁用('+'
)(一般来说你可以将其重命名,但是,你不想直接与ProductGroup
工作)。否则,我们会得到Reverse accessor for 'ProductGroup.child' clashes with reverse accessor for 'ProductGroup.parent'.
。为了在管理员中拥有很好的ManyToMany显示,我们必须使用内联模型(
ProductGroupInline
)。在文档中阅读有关它们。但请注意,fk_name
字段。我们必须指定这个,因为ProductGroup
本身是不明确的 - 这两个字段都是相同模型的外键。对再现性要小心。如果你想在
Product
上将__str__
定义为:return self.products
与ProductGroup
具有与孩子相同的父母,那么你将无限循环。
- 正如可以在撷取画面对看到现在可以重复。或者,您只需将数量字段添加到
ProductGroup
并在创建对象时检查重复。
你使用任何形式?这是你的完整模型吗? – itzMEonTV
该模型有更多的领域,但我删除它,因为问题是“the_products_inside_combo” – RaR
基本上我不能输入同一产品两次。这是唯一的问题。我可以使用文本字段(ID),但这对数据输入来说很难,因为他们需要手动输入ID而不是仅选择产品。 – RaR