我正在研究一个django项目。我有两个表,它们是组和组活动。组存储有关所创建组的信息。 GroupActivity存储与组相关的所有活动。例如,一个名为Welcome的组将存储在组表中,其中包含有关该组的信息。如果将成员添加到组中,则会在组活动表中显示活动记录。我想创建一个系统,允许我抓住某人所属的所有组,并为每个组抓取该用户所属的每个组所发生的最后一个活动。我尝试使用两个不同的查询并使用两个for循环,但它根本不起作用。任何人都可以帮助我..这是我的代码
以下是表格:
class Group(models.Model):
name = models.CharField(max_length = 25)
description = models.CharField(max_length = 250, null=True)
created_by = models.ForeignKey(User, default=1, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
class GroupActivity(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
expense = models.ForeignKey(Expense, null=True, on_delete=models.CASCADE)
bundle = models.ForeignKey(Bundle, on_delete=models.CASCADE, null=True)
description = models.CharField(max_length=200, default='some action')
host = models.CharField(max_length=100, null=True)
reference = models.IntegerField(default=0)
category = models.SmallIntegerField(default = 1)
created = models.DateTimeField(auto_now_add=True)
以下是我在views.py文件中的内容:
# ensure someone is logged in
@login_required(login_url='/login/')
# groups home page
def groups_home(request):
# grab the logged in user
user = request.user
# grab all of the groups you are a member of
groups = Member.objects.filter(user = user).all()
# everythin that is going to be passed to the html template
activities = GroupActivity.ojects.order_by('group').desc()
parameters = {
'groups':groups,
'activities':activities,
}
return render(request, 'groups/groups.html', parameters)
这是html模板:
{% for group in groups %}
<p>
<a href="{% url 'group_home' group.group.name|slugify group.group.id %}">{{ group.group.name }}</a>
</p>
{% endfor %}
示例:
two groups = Bros and Sisters
activity = Bros => josh was added
=> steve was added
=> josh sent steve a message
Sisters => jessica added jenny
=> jessica added julie
=> jessica added stephanie
I want to grab the two groups = Bros and Girls
I want to grab the actviities = josh sent steve a message
= jessica added stephanie
我想像应用程序主屏幕中的whatsapp组一样显示组和最后一个活动。
任何人都可以帮助我。
答案 0 :(得分:0)
而不是直接查询活动,你可以使用后向关系,在模板中使用这样的东西
{% for group in groups %}
<p>
<a href="{% url 'group_home' group.group.name|slugify group.group.id %}">{{ group.group.name }}</a>
</p>
{% for act in group.activity_set.all %}
{{ act.description }}
{% endfor %}
{% endfor %}
有关详情,请参阅django docs中的this页面。