aviraldg
aviraldg

Reputation: 9154

Django -- How to filter objects with an "author" from a set of "authors"(users)?

How to filter objects with an "author" from a set of "authors"(Users)?

The "objects" are Posts, having an author(ForeignKey to User).

I'm pretty much stumped by this, so I'd appreciate help with it. Of course one could go about this the naive way, by manually filtering them, but that would hit the database real hard. Thanks anyway.

EDIT: Listing of Post:

class Post(models.Model):
    '''A Post or a Status Update.
    '''
    content=models.CharField(max_length=200)
    author=models.ForeignKey(django.contrib.auth.models.User, related_name="author")
    tags=models.ManyToManyField(Tag)
    replyTo=models.ManyToManyField(django.contrib.auth.models.User, related_name="replyTo")
    # Snip model methods

Clarification: I'm trying to filter based upon a set of users and not a single user (which is trivially easy to do) when=models.DateTimeField(auto_now=True)

Thanks to everyone who helped with the previous question. Now I have one final thing to ask:

Code excerpt from UserProfile (connected to User):

def get_updates():
    return Post.objects.filter(author__in=(list(self.friends.all()) + [self]))

Is this the most efficient way to get all the posts by an author and its friends? (Note: This is a naive implementation, as it doesn't handle pagination, etc. Will do that later)

Upvotes: 3

Views: 10390

Answers (3)

Sreejit Kar
Sreejit Kar

Reputation: 1

Post.objects.filter(attribute__in = list_of_ids)

Upvotes: 0

Zach
Zach

Reputation: 19082

Something like:

Post.objects.filter(author=user)

Where user is the relevant user should work, but it's hard to give a good answer with no models

EDIT

Now that I understand your question, try this:

Post.objects.filter(author__in=users)

Where users is the set of users

Upvotes: 6

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

Post.objects.filter(author__in=setofusers)

Upvotes: 5

Related Questions