2017-05-09 284 views
0
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关系,从产品和到 产品已经存在。

Screencap of the error.

+0

你使用任何形式?这是你的完整模型吗? – itzMEonTV

+0

该模型有更多的领域,但我删除它,因为问题是“the_products_inside_combo” – RaR

+0

基本上我不能输入同一产品两次。这是唯一的问题。我可以使用文本字段(ID),但这对数据输入来说很难,因为他们需要手动输入ID而不是仅选择产品。 – RaR

回答

0

每对(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关系进行建模与ProductGroupthrough参数)。几条注释:

  1. 带中间表的多对多字段不能是对称的,因此symmetrical=FalseDetails

  2. ProductGroup反向存取被禁用('+')(一般来说你可以将其重命名,但是,你不想直接与ProductGroup工作)。否则,我们会得到Reverse accessor for 'ProductGroup.child' clashes with reverse accessor for 'ProductGroup.parent'.

  3. 为了在管理员中拥有很好的ManyToMany显示,我们必须使用内联模型(ProductGroupInline)。在文档中阅读有关它们。但请注意,fk_name字段。我们必须指定这个,因为ProductGroup本身是不明确的 - 这两个字段都是相同模型的外键。

  4. 对再现性要小心。如果你想在Product上将__str__定义为:return self.productsProductGroup具有与孩子相同的父母,那么你将无限循环。

Admin example

  1. 正如可以在撷取画面对看到现在可以重复。或者,您只需将数量字段添加到ProductGroup并在创建对象时检查重复。
+0

我很抱歉,但我对此很新。你能给出一个简单的代码示例与管理员模型代码? – RaR

+0

当然,我更新了我的答案。 – Siegmeyer

+0

非常感谢 – RaR

相关问题