【问题标题】:Django: m2m on a subclassed objectDjango:子类对象上的 m2m
【发布时间】:2017-05-03 09:11:53
【问题描述】:

我在我的项目中为产品和类别使用墨盒和夹层,并且我正在尝试将 ManyToManyField 添加到我的自定义模型中。

from cartridge.shop.models import Product, Category

class BaseProduct(Product):
    (...)
    related_categories = models.ManyToManyField(Category, blank=True, through='CategoryLink')

class CategoryLink(models.Model):
    category = models.ForeignKey(Category)
    product = models.ForeignKey(BaseProduct)

为了完整起见,他们的模型是:

分类:https://github.com/stephenmcd/cartridge/blob/master/cartridge/shop/models.py#L341

产品:https://github.com/stephenmcd/cartridge/blob/master/cartridge/shop/models.py#L105

但是,当我尝试执行迁移时,这给了我以下错误:

Operations to perform:
  Apply all migrations: admin, auth, blog, brochures, case_studies, conf, contenttypes, core, django_comments, forms, galleries, generic, mezzanine_blocks, pages, quotes, redirects, services, sessions, shop, sites, stevensons_shop, stevensons_user, twitter, utilities
Running migrations:
  Applying stevensons_shop.0057_baseproduct_related_categories...Traceback (most recent call last):
  File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: there is no unique constraint matching given keys for referenced table "stevensons_shop_baseproduct"

我做错了什么?甚至可以在子类对象上添加 m2m 吗?我需要对 Category 模型进行修改吗?

【问题讨论】:

    标签: python django many-to-many


    【解决方案1】:

    您有一个模型 BaseProduct 与 Category 具有 m2m 关系。

    模型 CategoryLink 是该 m2m 关系的重复。 它是python的禅宗,你违反了。 “不要重复自己”。 删除该 m2m 字段或映射表(CategoryLink)。 这应该可以正常工作。

    我个人建议使用映射表而不是 m2m 字段。 在我看来,它更敏捷。

    希望你得到你的要求。

    【讨论】:

    • 感谢您的回复。我认为 BaseProduct m2m 的“through='CategoryLink'”部分应该促进两者?对于它的价值,我正在尝试遵循docs.djangoproject.com/en/dev/topics/db/models/… 的指南
    • 有时,在 m2m 关系中显式声明外键可能会导致麻烦。座右铭是保持简单,不是吗!!?
    猜你喜欢
    • 1970-01-01
    • 2016-06-18
    • 2015-06-23
    • 2011-12-26
    • 1970-01-01
    • 2020-05-03
    • 2013-02-24
    • 1970-01-01
    • 2020-02-15
    相关资源
    最近更新 更多