Asma Gheisari
Asma Gheisari

Reputation: 6254

how to use "where in" clause

I have these models:

class AgencyPosition(models.Model):
   Agency=models.ForeignKey(Agency)
   Users=models.ManyToManyField(User)
   PositionTypeCode=models.ForeignKey(PositionType)
   PhoneNumber=models.CharField(max_length=50)
   Email=models.CharField(max_length=50)
   StatusTypeCode=models.ForeignKey(StatusType)

class News(models.Model):
   Category=models.ForeignKey(Category)
   Title=models.CharField(max_length=100)
   Description=models.TextField()
   created_by=models.ForeignKey(User,editable=False)
   ActionDate=models.DateTimeField(auto_now=True,editable=False)

I wanna when user enter the name of an Agency I select top 5 news belong to specific agency.News model have an created_by field.created_by field is the user that insert that News.in AgencyPosition I determine user belong to which Agency.

I do this in views.py:

agn=Agency.objects.filter(Name=key)
AgencyPositionList=AgencyPosition.objects.filter(Agency=agn)

now I have all users from the specific Agency.then I wanna select News that their Created_by field is for that specific Agency.some thing like this pseudo code:

select top 5 * from News where created_by in(AgencyPositionList.Users)

How can I do this?

Upvotes: 1

Views: 113

Answers (2)

Melug
Melug

Reputation: 1031

Try this:

News.objects.filter(created_by__agency_position__id=your_agency_id)[:5]

Upvotes: 1

Cat Plus Plus
Cat Plus Plus

Reputation: 129764

News.objects.filter(created_by__in = AgencyPositionList.Users)[:5]. It's all documented.

Upvotes: 2

Related Questions