简体   繁体   English

Django,ManyToManyField(model),同时定义模型

[英]Django, ManyToManyField(model) while defining model

I'm new to Django and I've encountered some problem: I'm trying to prepare website where users can attach themselves to custom model "UserGroup" (not these from User.group) so they'll become it's members as ManyToManyField relation. 我是Django的新手,遇到了一些问题:我正在尝试准备一个网站,以便用户可以将其附加到自定义模型“ UserGroup”(不是来自User.group的这些模型)中,以便他们成为ManyToManyField关系的成员。 But I would like also to add information to these groups whether they're linked to other groups. 但是我也想向这些组添加信息,无论它们是否链接到其他组。 How can do such thing? 怎么可以这样呢? I've tried to do this like here, in UserGroup definition: 我尝试在UserGroup定义中执行以下操作:

related_groups = models.ManyToManyField('UserGroup', blank=True)

But apparently I can't do that this way, I'm getting some problems during migration: 但是显然我不能这样,在迁移过程中遇到了一些问题:

django.core.exceptions.FieldDoesNotExist: UserGroup_related_groups has no field named 'from_usergroup ' django.core.exceptions.FieldDoesNotExist: UserGroup_related_groups has no field named 'from_usergroup ”的django.core.exceptions.FieldDoesNotExist: UserGroup_related_groups has no field named 'from_usergroup

I suppose it might be because of faulty way of thinking. 我想可能是因为思维方式错误。 Thanks for help in advance! 预先感谢您的帮助! :) :)

  1. You are using wrong name of class for user groups. 您为用户组使用了错误的类名称。 The correct name is Group 正确的名称是
  2. You should use OneToOne Field. 您应该使用OneToOne字段。

So you should write something like: 因此,您应该编写如下内容:

related_groups = models.OneToOneField('Group', blank=True)

And don't forget to import Group model before! 并且不要忘了导入Group模型!

from django.contrib.auth.models import Group

PS There are 2 ways to do this: 1) To make your own class (ie ExtGroup) and make OneToOneField to original Group Class. PS有两种方法可以做到这一点:1)创建自己的类(即ExtGroup)并将OneToOneField设置为原始组类。 You probably were trying to go this way. 您可能正在尝试采用这种方式。 2) Use your own user class and group class. 2)使用您自己的用户类和组类。

Here is really nice documentation about each way: https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#extending-the-existing-user-model 这是关于每种方法的非常不错的文档: https : //docs.djangoproject.com/en/1.10/topics/auth/customizing/#extending-the-existing-user-model

And here is answer for the same question: Customize Django Group Model 这是相同问题的答案: 自定义Django组模型

Hope it helps ;) 希望能帮助到你 ;)

Use "self" to indicate that you are linking to the same class. 使用“自我”表示您正在链接到相同的类。

related_groups = models.ManyToManyField("self", blank=True)

As suggested in this SO post Django Many-to-Many (m2m) Relation to same model 正如本SO帖子中所建议的, Django与同一个模型的多对多(m2m)关系

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM