【发布时间】:2017-04-12 15:02:28
【问题描述】:
我在 Django 中有一个模型,它有一个名为“accepted_insurance”的多对多字段。我有一个表单,它使用包含保险提供商列表的查询字符串提交获取请求。我正在尝试编写一个查询,上面写着“如果查询字符串列表中的任何项目都在多对多字段列表中,则过滤这些对象。”。是否有 Django 查询快捷方式?我尝试使用“包含”,但我收到了一个类型错误,即相关字段的查找无效,我确信这只会说明列表是否包含列表。
models.py
class Provider(models.Model):
title = models.CharField(max_length=255, null=True, blank=True)
first_name = models.CharField(max_length=255, null=True, blank=True)
middle_name = models.CharField(max_length=255, null=True, blank=True)
last_name = models.CharField(max_length=255, null=True, blank=True)
email = models.EmailField(null=True, blank=True)
phone = models.CharField(max_length=40, null=True, blank=True)
extension = models.CharField(max_length=10, null=True, blank=True)
company = models.CharField(max_length=255, null=True, blank=True)
age = models.IntegerField(null=True, blank=True)
about = models.TextField(default='', null=True, blank=True)
position = models.CharField(max_length=255, null=True, blank=True)
cost_per_session = models.CharField(max_length=255, null=True, blank=True)
accepts_insurance = models.BooleanField(default=False)
accepted_insurance = models.ManyToManyField('Insurance', blank=True)
payment_methods = models.ManyToManyField('PaymentMethod', blank=True)
request.GET
http://localhost:8004/directory/?search=timothy&insurance=cigna,aetna,optum_health,united_behavioral,blue_cross_blue_shield
<QueryDict: {'insurance': ['cigna,aetna,optum_health,united_behavioral,blue_cross_blue_shield'], 'search': ['timothy']}>
views.py 查询
for param in request.GET:
if param.lower() == 'insurance':
all_providers = all_providers.filter(accepted_insurance__contains=param)
【问题讨论】:
标签: django model get many-to-many