我需要有一个没有任何组的用户的视图。我曾尝试使用.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
send 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'
答案 0 :(得分: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)
另外,您的模型设计看起来有点偏斜,相同的引用相互交叉。并且不需要添加后向引用(例如在模型`Course中)。 Django为您提供了向后引用的功能。见https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward
答案 1 :(得分:0)
因此,当删除了向后引用时,我在ManyToManyField和Rahul的回答中使用了related_name
并进行了一些编辑:
groupless = User.objects.filter(course_list__assignment=detailedassignment).exclude(group_list__assignment=detailedassignment)
如果它有用..:D