3

我有一个状态模型。它很好地显示了所有状态。现在我想要的是在用户页面中显示特定用户的所有状态或活动。如何查询特定用户status的所有和?liked 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)

请检查并指导我。谢谢!

4

2 回答 2

1
Status.objects.filter(creator__id=6)
Like.objects.filter(liked__id=6)
于 2013-09-10T17:02:35.893 回答
1

它应该是:

u.creator_set.all()

注意,你已经穿上related_name=creator_set了 FK。

编辑:为用户点赞:

u.like_set.all()

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

[each.status for each in u.like_set.all()]
于 2013-09-10T17:06:20.693 回答