简体   繁体   中英

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?

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

尝试这个:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM