Django过滤器中间表&社交媒体

时间:2015-12-13 21:37:19

标签: django django-models django-forms django-templates django-views

所以我正在用社交媒体网站练习django(仅供练习)。我正试图在我的视图中做一个过滤器来获取用户的所有“Beats”我是他的朋友。我使用中间表表示“关系”。我目前正在使用以下方式获取Beat Stream:

my_stream = Beat.objects.filter(artist=user)

但是我试图在关系模型中只得到人们的节奏。“

模型:

class Beat(models.Model):
    created_at = models.DateTimeField( default=datetime.now)
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True, null=True)
    likes = models.IntegerField(default=0)
    artist = models.ForeignKey(User, null=True, blank=True)
    beat_cover = models.ImageField(null=True, blank=True);
    admin_name = models.CharField(max_length=255, blank=True, null=True)

    class Meta:
        ordering = ['-created_at']

    def __unicode__(self):
        return unicode(self.admin_name)

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    admin_name = models.CharField(default="beat",max_length=255,blank=True, null=True)

    def __unicode__(self):
        return unicode(self.admin_name)

class Relationship(models.Model):
    from_user = models.ForeignKey(User, related_name="relationships")
    to_user = models.ForeignKey(User, related_name="related_to")

    class Meta:
        index_together = ['from_user','to_user']

1 个答案:

答案 0 :(得分:0)

你应该这样做:

related_users = Relationship.objects.filter(from_user=user) \
                                    .values_list('to_user', flat=True).distinct()
my_stream = Beat.objects.filter(artist__in=related_users)