0

我需要查看没有任何组的用户。我试图进行查询, .except但由于许多字段而失败...

我的模型:

class UserProfile(models.Model):
    user = models.OneToOneField(User, unique=True)
    courses_list = models.ManyToManyField('Course', blank=True)
    group_list = models.ManyToManyField('Group', blank=True)

class Group(models.Model):
    name = models.CharField(max_length=30)
    assignment = models.ForeignKey(Assignment)
    members = models.ManyToManyField(UserProfile, through=UserProfile.group_list.through, blank=True)

class Assignment (models.Model):
    course = models.ForeignKey(Course)

class Course(models.Model):
    subscribed = models.ManyToManyField(UserProfile, through= UserProfile.courses_list.through, blank=True)

所以,我需要选择订阅了assignment.course.subscribed.all没有任何组的作业(全部发送)的用户(问题是我只需要处理与此作业相关的组)

我试过groupless = detailedassignment.course.subscribed.exclude(username = group_list.filter(assignment=detailedassignment).members.username.all())了,但它根本不起作用(我认为当我看到代码时这是正常的..)

编辑 :

我以某种方式删除了关系,现在我的模型是:

My models :

class UserProfile(models.Model):
    user = models.OneToOneField(User, unique=True)

class Group(models.Model):
    name = models.CharField(max_length=30)
    assignment = models.ForeignKey(Assignment)
    members = models.ManyToManyField(UserProfile, blank=True)

class Assignment (models.Model):
    course = models.ForeignKey(Course)

class Course(models.Model):
    subscribed = models.ManyToManyField(UserProfile, blank=True)

我试过使用:

groupless = detailedassignment.course.subscribed.exclude(user__username__in = Group.objects.filter(assignment=detailedassignment).members.objects.values_list('user__username'))

但是我有'QuerySet' object has no attribute 'members'

4

2 回答 2

1

你忘记了user参考。因此,如果我正确地解释您,您会想要-

groupless = detailedassignment.course.subscribed.exclude(user__username__in = group_list.filter(assignment=detailedassignment).members.objects.values_list('user__username'))

或者试试这个 -

groupless = UserProfile.objects.filter(courses_list__assignment = detailedassignment).exclude(group_list__assignment=detailedassignment)

顺便说一句,您的模型设计看起来有些倾斜,相同的参考相互交叉。并且不需要添加反向引用(如模型“课程”中)。Django 为您提供了向后引用的功能。请参阅https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward

于 2012-07-26T11:55:35.737 回答
0

因此,当向后引用被删除时,我related_name在 ManyToManyField 和 Rahul 的回答中使用了 a 并稍作编辑:

groupless = User.objects.filter(course_list__assignment=detailedassignment).exclude(group_list__assignment=detailedassignment)

如果有用的话.. :D

于 2012-07-26T16:17:50.060 回答