如何在django中查询用户的模型

时间:2013-09-10 16:58:45

标签: django django-models django-views

我有一个状态模型。它很好地显示了所有状态。现在我想要的是在用户页面中显示特定用户的所有状态或活动。如何查询特定用户的所有statusliked status

如果我错了,请纠正我。我在shell中尝试了这个,但它显示为空:

>>> from status.models import *
>>> from django.contrib.auth.models import User
>>> s = Status.objects.get(id=3)
>>> s
<Status: sdfjsdklsdf>
>>> s.creator
<User: test2@gmail.com>
>>> u = User.objects.get(id=6)
>>> u
<User: test2@gmail.com>
>>> u.status_set.all()
[]
>>>

这是我的models.py:

from django.db import models
from django.contrib.auth.models import User
from datetime import datetime
from time import time


def get_upload_file_name(instance, filename):
    return "uploaded_files/%s_%s" %(str(time()).replace('.','_'), filename)

class Status(models.Model):
    status = models.TextField()
    image = models.ImageField(upload_to=get_upload_file_name, blank=True)
    pub_date = models.DateTimeField(default=datetime.now)
    creator = models.ForeignKey(User, related_name="creator_set")
    likes = models.ManyToManyField(User, through="Like")

    class Meta:
        ordering = ['-pub_date']
        verbose_name_plural = ('Status')

    def __unicode__(self):
        return self.status

class Like(models.Model):
    status = models.ForeignKey(Status)
    liked = models.ForeignKey(User)
    liked_date = models.DateTimeField(default=datetime.now)

    def __unicode__(self):
        return "%s likes %s" % (self.liked, self.status)

请检查并指导我。谢谢!

2 个答案:

答案 0 :(得分:1)

Status.objects.filter(creator__id=6)
Like.objects.filter(liked__id=6)

答案 1 :(得分:1)

应该是:

u.creator_set.all()

注意,您已将related_name=creator_set放在FK上。

编辑: 获取用户的喜欢:

u.like_set.all()

如果你想要喜欢的相应状态:

[each.status for each in u.like_set.all()]