DJANGO MPTT多个参考类对象

发布于 2025-02-09 20:02:45 字数 505 浏览 0 评论 0原文

我需要为香料制作模型。有些香料可能由其他香料组成,也可能是基本的。我需要具有多选择选项的TreeForeignkey之类的东西。我试图使用Treemanytomanyfield,但我无法为那里的基本香料设置为空。这是我的代码:

class Goods(MPTTModel):
    category = models.ForeignKey(Category,
                                 related_name='goods',
                                 on_delete=models.SET_NULL,
                                 null=True)    
    name = models.CharField(max_length=150, db_index=True)
    parent = TreeManyToManyField(
        'self',
        blank=True,)

I need to make a model for spices. Some spices may consist of others, or be basic. I need something like TreeForeignKey with multi-select option. I tried to use TreeManyToManyField, but I can't set null for base spices there. Here is my code:

class Goods(MPTTModel):
    category = models.ForeignKey(Category,
                                 related_name='goods',
                                 on_delete=models.SET_NULL,
                                 null=True)    
    name = models.CharField(max_length=150, db_index=True)
    parent = TreeManyToManyField(
        'self',
        blank=True,)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

全部不再 2025-02-16 20:02:45

MPTT并不适合您的要求。在树中,每个节点只有1个父(或根节点的父)。但是,在您的情况下:

  • 碱性香料的组合香料
  • 可以在许多组合香料中使用许多

,这是一种多到多的关系。请参阅 https:// https://djangoproject.com/en/en/en/en/4.0/4.0/4.0/4.0/4.0/4.0/4.0/主题/db/示例/many_to_many/

您的模型看起来像:

class Spice(models.Model):
    ingredients = models.ManyToManyField("self", blank=True)

An MPTT isn't a good fit for what you are asking. In a tree, each node has only 1 parent (or no parent for a root node). But, in your case:

  • A combination spice could be made of many base spices
  • A base spice could be used in many combination spices

This is a many-to-many relationship. See https://docs.djangoproject.com/en/4.0/topics/db/examples/many_to_many/

Your model could look something like:

class Spice(models.Model):
    ingredients = models.ManyToManyField("self", blank=True)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文