我无法理解我应该如何获取包含用户的组的查询集,我已经尝试了_set,prefetch_select,但仍然没有结果。
class User(AbstractUser):
...
class Group(models.Model):
...
Member_list = models.ManyToManyField(User, through='Member', related_name="Member_list")
class Member(models.Model):
group = models.ForeignKey(Group)
user = models.ForeignKey(User)
...
我需要获取与该用户关联的所有组,例如 Member.objects.filter(user == request.user)
的组我在尝试:
user = request.user
groups = user.group_set.all() # empty list :(
member = user.member_set.all() # works currectly, returns my 1 test group
答案 0 :(得分:1)
我只是创建你的基础。创建组,用户并连接它们:
u = User.objects.create(name='user')
g = Group.objects.create()
m = Member.objects.create(group=g, user=u)
在此之后我可以得到这样的用户组:
u.Member_list.all()
# output: [<Group: Group object>]
我的基地:
class User(models.Model):
name = models.CharField(max_length=4)
class Group(models.Model):
Member_list = models.ManyToManyField(User, through='Member', related_name="Member_list")
class Member(models.Model):
group = models.ForeignKey(Group)
user = models.ForeignKey(User)