这是我的模型设计:
class Group(models.Model):
name = models.CharField(max_length=30)
...
class User(models.Model):
name = models.CharField(max_length=50)
...
group = models.ForeignKey(Group)
class Photo(models.Model):
title = models.CharField(max_length=100)
...
user = models.ForeignKey(User)
如何获得所有组的列表,在每个组下属于该组的用户的 5 张随机照片?
我试过:
g = Group.objects.all()
for group in g:
r = Photo.objects.filter(user.group=group).order_by('?')[:5]
那就是给:
Django Version: 1.4.3
Exception Type: SyntaxError
Exception Value:
keyword can't be an expression (views.py, line 37)
Exception Location: /PATH/python2.7/site-packages/django/utils/importlib.py in import_module, line 35
Python Executable: /PATH/python
Python Version: 2.7.3
但即使我的代码有效,我也不认为这是理想的方式,因为它会产生太多的查询。
请帮忙。