Django查询使用过滤器

时间:2011-05-08 23:06:41

标签: django django-models

我在django中有3个模型:

class Movie(models.Model):
    mid = models.IntegerField(primary_key = True)
    name = models.CharField(max_length = 100)

class User(models.Model):
    username = models.CharField(max_length=128, null=True)
    uid = models.CharField(max_length=100)
    movie = models.ManyToManyField(Movie, through = "Vote")

class Vote(models.Model):
    movie = models.ForeignKey(Movie)
    user = models.ForeignKey(User)
    rating = models.IntegerField()

这里评级= 0 / 1,0表示不喜欢,1表示喜欢 我想使用过滤器进行一些查询:

  1. 找出当前用户喜欢的所有电影。为此,我使用以下2个查询,但它们都不起作用。在这两种情况下,它都会产生错误的结果

    ans = Movie.objects.filter(vote__user = self).filter(vote__rating = 1)

    ans = Movie.objects.filter(user__uid = self.uid).filter(vote__rating = 1)

  2. 我有一个数组 ID 的用户列表。我想知道这个列表中有多少用户喜欢特定的电影? 我试过这个,但这也是不正确的:

    ret = User.objects.filter(uid__in = ids).filter(vote__movie = mov).filter(vote__rating = 1)

  3. 有人可以帮我解决这两个问题吗?

1 个答案:

答案 0 :(得分:1)

我还建议让django分配模型的id,但是如果你使用遗留数据库或者由于某些其他原因需要分配id,你可以这样查询:

  1. # uid is some uid
    user = User.objects.get(uid=uid)
    likes = Movie.objects.filter(vote__user=user, vote__rating=1)
    

    likes = Movie.objects.filter(vote__user__uid=some_uid, vote__rating=1)
    
  2. 喜欢特定电影的用户列表中的人数:

    >>> uids = ['1','2','3']
    >>> # if mov is a Movie instance
    >>> votes = Vote.objects.filter(user__uid__in=uids, movie=mov, rating=1)
    >>> print votes.query
    SELECT "so1_vote"."id", "so1_vote"."movie_id", "so1_vote"."user_id", "so1_vote"."rating" FROM "so1_vote" INNER JOIN "so1_user" ON ("so1_vote"."user_id" = "so1_user"."id") WHERE ("so1_user"."uid" IN (1, 2, 3) AND "so1_vote"."movie_id" = 1  AND "so1_vote"."rating" = 1 )
    >>> # if mov is a mid for a movie
    >>> # get movie instance by using Movie.objects.get(mid=mov)
    >>> # or query:
    >>> # votes = Vote.objects.filter(user__uid__in=uids, movie__mid=mov, rating=1)
    >>> likes_count = votes.count()
    >>> print likes_count
    0
    

    组合:

    likes_count = Votes.objects.filter(user__uid__in=uids, movie=mov, rating=1).count()