我有一个配置文件表,其中包含用户的外键。
class Profile(models.Model):
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
image = models.CharField(max_length=100)
user = models.ForeignKey(User)
我还有一个COMMENT表,其中包含用户的外键。
class Comment(models.Model):
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
content = models.TextField()
user = models.ForeignKey(User)
我想查询表COMMENT,并且我想获取PROFILE表中用户的图像。如何在django中以最有效的方式查询?
感谢
答案 0 :(得分:1)
如果您可以在Profile模型上将ForeignKey更改为OneToOneField,那么您可以这样做,
Comment.objects.all().select_related('user__profile')
上面的一个在执行查询时选择其他相关对象数据。这是一个性能提升器,它会导致单个更复杂的查询,但意味着以后使用外键关系不需要数据库查询。
否则你可以这样做
for comment in Comment.objects.all():
print comment.user.profile_set.all()[0].image
答案 1 :(得分:0)
如果您正在使用Django =< 1.4,则以下是最佳做法:
comment = Comment.objects.get(pk=1)
comment.user.get_profile().image
在弃用本机Profile
模型支持(Django 1.5+)之后,仍然可以使用以下内容:
comment = Comment.objects.get(pk=1)
comment.user.profile.image
Django 1.5+引入了自定义身份验证模型,因此您可以执行以下操作:
comment = Comment.objects.get(pk=1)
comment.user.image
至少,您应该在ForeignKey
上将用户列的OneToOne
更改为Profile
关系,因为Django =< 1.4预计只有一个User Profile
与User
相关联。
参考文献:
Django 1.4 get_profile
:https://docs.djangoproject.com/en/1.4/topics/auth/#django.contrib.auth.models.User.get_profile
Django 1.5+扩展用户模型: https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#extending-the-existing-user-model