我有以下Django模型
class Post(models.Model):
author = models.ForeignKey(CustomUser,on_delete=models.CASCADE,)
title = models.CharField(max_length=200,null=True)
text = models.TextField()
post_url = models.URLField(max_length = 200, blank = True)
post_tier = models.ForeignKey(Tiers, on_delete=models.CASCADE, null= True)
post_tier_value = models.IntegerField(default=0)
slug = models.SlugField(unique=True, blank=True)
我有author_list = [author1@gmail.com, author2@gmail.com]
和tier_value_list = [2000,3000]
。我想在上述模型中查询(author = author1@gmail.com and post_tier_value <= 2000)
或(author = author2@gmail.com and post_tier_value <= 3000)
。
有人可以帮我查询一下吗?
答案 0 :(得分:1)
使用 Q()
运算符
from django.db.models import Q
author_list = ['author1@gmail.com', 'author2@gmail.com']
tier_value_list = [2000, 3000]
query = Q()
for author, value in zip(author_list, tier_value_list):
query = query | Q(author=author, post_tier_value__lte=value)
Post.objects.filter(query)
注意::我使用的是 author__email
,它是自{{ 1}}包含email_ids