python - 如何使用 "where in"子句

标签 python django

我有这些模型:

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)

我想当用户输入代理名称时,我选择属于特定代理的前 5 条新闻。新闻模型有一个created_by 字段。created_by 字段是插入该新闻的用户。在 AgencyPosition 中我确定用户属于哪个代理。

我在views.py中执行此操作:

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

现在我拥有来自特定代理机构的所有用户。然后我想选择新闻,他们的 Created_by 字段适用于该特定代理机构。像这样的伪代码:

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

我该怎么做?

最佳答案

News.objects.filter(created_by__in = AgencyPositionList.Users)[:5]。都是documented .

关于python - 如何使用 "where in"子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7731859/

相关文章:

python - 如何处理图像分类的可变图像尺寸?

python - 为什么 django 有collectstatic?

django - 在DRF中嵌套ViewSet路线

Django CSRF_COOKIE_DOMAIN - 如何优雅地改变

python - 打印生成的随机字符串

python - 我有所有棒球运动员的国家、开始和结束年份。我需要知道每个国家每年有多少球员参加比赛

Python iloc 给出 indexError : single positional indexer is out-of-bounds in simple for loop

python - 为什么当我更改一个变量时,两个变量都会更改? Python

python - 以两列为条件并创建第三列失败的 Pandas Python

python - Django REST 框架和文件上传(数据 URI)