Domanda

I was make a microblogging like twitter and I want to list the posts of users that authenticated user is following.

Models:

class Post(models.Model):
    post = models.TextField(max_length=300)
    created = models.DateTimeField(auto_now=True)
    user = models.ForeignKey(User)

    def __unicode__(self):
        return self.post

class UserProfile(models.Model):
    USER_SEX = (
        ('M', 'Masculino'),
        ('F', 'Femenino'),
    )
    birthday = models.DateField(null=False)
    sex = models.CharField(max_length=1, choices=USER_SEX)
    description = models.TextField(max_length=100, null=True)
    location = models.CharField(blank=True, max_length=100, null=True)
    user = models.OneToOneField(User)
    follows = models.ManyToManyField('UserProfile', related_name='followed_by', blank=True, symmetrical=False)

    def __unicode__(self):
            return self.user.get_username()

Views:

def show_posts(request):
    user = request.user
    following = user.userprofile.follows.all()
    posts = Post.objects.filter(user__in=following).order_by('-created')
    return render_to_response("posts.html", context_instance = RequestContext(request, {'posts':posts}))

This function return all posts of all users, except the authenticated user. I don't want this. I want to show all posts of users ONLY the user authenticated is following and also the posts of the user authenticated.

Someone can help me?

È stato utile?

Soluzione

I'm not sure of my answer, but nobody answered, so here's my try.

following is a QuerySet, which becomes a list of UserProfile, but you filter on user__in, which is a list of User. Can you try making follows a ManyToManyField to User instead and tell us the results? Even if you still have the same problem, the filter will make more sense!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top