DJANGO MPTT多个参考类对象
我需要为香料制作模型。有些香料可能由其他香料组成,也可能是基本的。我需要具有多选择选项的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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
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/
您的模型看起来像:
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:
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: