在外键上按字段过滤

问题描述 投票:0回答:3

我有两个相互关联的模型

class IndustryService(models.Model):    
    title = models.CharField(max_length=120)
    pricingisarate = models.BooleanField(default=False) 

class UserService(models.Model):  
    user = models.ForeignKey(User, on_delete=models.CASCADE) 
    title = models.ForeignKey(IndustryService, on_delete=models.CASCADE, null=True, blank=True)

在视图中,我正在尝试开发一个UserService实例的查询集

a)属于用户

b)关于外键,有pricingisarate == True

我尝试了以下查询,但它不起作用:

 services = UserService.objects.filter(user=user, industryservice__pricingisarate__is=True)

谢谢你的帮助!!!

python django django-models django-views
3个回答
0
投票

得到它了!

services = UserService.objects.filter(user=user, title__pricingisarate=True)

0
投票

您可以通过在外键定义的名称和要由此过滤的子字段名称之间使用双下划线来过滤外键字段,对于您的情况,它类似于下面:

title__pricingisarate

您的查询必须更改如下:

services = UserService.objects.filter(user=user, title__pricingisarate=True)

一些formal examples of Django about this article可用...


0
投票
services = UserService.objects.filter(user=user, title__pricingisarate=True)

因为UserService与使用查找标题的IndustryService模型有关。

请参考此链接 - https://docs.djangoproject.com/en/2.1/topics/db/queries/#lookups-that-span-relationships

© www.soinside.com 2019 - 2024. All rights reserved.