我有User(Django内置),Reports,ReportGroups和ReportGroupMembers的模型。用户可以创建属于单个ReportGroup的报表。用户只能为他们所属的ReportGroup编写报告(因此ReportGroupMembers)。
在我看来(下方),我只想展示用户拥有的群组,或者是其中的一员,并且有一个装饰者或者某种方式可以轻易地阻止人们写入他们不属于的群组。 ReportGroups 可以关联密码(用于加入组)。我不太确定设计/实现这一目标的最佳方法,并且能够很好地扩展。如果我不需要它来扩展我只是为了循环迭代它们所属的组。
查看:
owned_group_list = ReportGroup.objects.filter(user=request.user.id)
member_group_list = ReportGroupMember.objects.filter(user=request.user.id)
group_list = owned_group_list | member_group_list
return render(request, 'dashboard/main.html', {'group_list': group_list})
这不起作用,因为它抱怨"无法在两个不同的基本模型上组合查询。"
型号:
class ReportGroup(models.Model):
group_name = models.CharField(max_length=64, blank=False, null=False)
description = models.TextField(blank=True, null=True)
avatar = models.ImageField(upload_to='profiles', null=True, blank=True)
user = models.ForeignKey(User)
class Meta:
managed = True
db_table = 'report_group'
def __str__(self):
return 'Group: %s - User: %s' % (self.group_name, self.user.username)
class Report(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=264, unique=False)
users = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
group = models.OneToOneField(ReportGroup, on_delete=models.CASCADE)
class Meta:
managed = True
db_table = 'intelligence_report'
def __str__(self):
return '%s (%s)' % (self.name, self.users.username)
class ReportGroupMembers(models.Model):
groups = models.ForeignKey(ReportGroup, on_delete=models.CASCADE)
users = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class Meta:
managed = True
db_table = 'report_group_membership'
def __str__(self):
return 'Group: %s - User: %s' % (self.groups, self.users)
答案 0 :(得分:0)
想出来:
owned_group_list = ReportGroup.objects.filter(user=request.user.id)
member_group = ReportGroupMember.objects.filter(user_id=request.user.id)
group_list = ReportGroup.objects.filter(
Q(id__in=member_group.values_list('group_id')) | Q(id__in=owned_group_list.values_list('id')))
return render(request, 'dashboard/main.html', {'group_list': group_list})