重构 Django 查询

Refactoring Django query

为了从我的数据库中提取数据,我写了一些说明。 我有两个价值观;城市名称和关键字,它们是 AddressMuseum:

的属性
class Museum(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=200)
    address = models.ForeignKey(Address)
    description = models.CharField(max_length=200)

class Address(models.Model):
    id = models.AutoField(primary_key=True)
    streetAddress = models.CharField(max_length=200)
    city = models.CharField(max_length=200)

现在我收到两个可选参数:一个城市和一个关键字。我想根据这样的城市过滤掉博物馆(完全匹配)AND这样的关键字(名称部分匹配OR描述)

这是我最后写的:

if city is not None and keyword is None:
    city_data = Address.objects.all().filter(city=city)
    museum_list = Museum.objects.all().filter(address__in=city_data)

elif city is None and keyword is not None:  
    museum_list = Museum.objects.all().filter(
        Q(name__contains=keyword) | Q(description__contains=keyword)
    )

elif city is not None and keyword is not None:      
    city_data = Address.objects.all().filter(city=city)
    museum_list = Museum.objects.all().filter(
        Q(address__in=city_data) & (
            Q(name__contains = keyword) | Q(description__contains=keyword)
        )
    )
else:
    museum_list = Museum.objects.all()  

我不喜欢这段代码,因为我考虑了所有可能的组合。我如何使用 Django 过滤将此类代码改进为:

results = Museum.objects.all()
if city not null
   results = results.filterByAddress_City
if keyword not null
   results = results.filterByKeywordLikeNameOrLikeDescription

谢谢。

查询是可组合的,因此您几乎可以完全按照伪代码中的说明进行操作。

results = Museum.objects.all()
if city:
   results = results.filter(address__city=city)
if keyword:
   results = results.filter(Q(name__contains = keyword) | Q(description__contains = keyword))