Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 663
aviraldg Avatar asked Dec 23 '22 05:12

aviraldg


2 Answers

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

like image 197
Zach Avatar answered Mar 08 '23 23:03

Zach


Post.objects.filter(author__in=setofusers)
like image 22
Ignacio Vazquez-Abrams Avatar answered Mar 09 '23 01:03

Ignacio Vazquez-Abrams