python - Django数据库: how to filter objects based on other object's field?

标签 python django

在下面的代码中,如何过滤 capital_listings 以便仅返回首府城市的列表?另外,是否可以去掉中间的capitals_names列表?

capitals = City.objects.filter(status='capital')
capitals_names = [capital.name for capital in capitals]
capital_listings = Listing.objects.filter #???

型号:

class Listing(models.Model):
    city = models.CharField(max_length = 30, default = 'placeholder')
    date_added = models.DateTimeField()

    def __str__(self):
        return self.name

class City(models.Model):
    name = models.CharField(max_length = 30, default = 'placeholder')
    status = models.CharField(max_length = 30, default = 'placeholder')

    def __str__(self):
        return self.name

最佳答案

capital_listings = Listing.objects.filter(city__in=capital_names)

关于python - Django数据库: how to filter objects based on other object's field?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51808979/

相关文章:

python - python 中 ReLU 函数的 ValueError

django - 在 Django Admin 中只获取与实例相关的项目

django - 为什么我需要一个单独的 Django 网络服务器?

python - 在模板中使用 Django 设置

python - Ubuntu 为 Django 设置环境变量

python - .fit_transform 方法的输出

python - 遍历 django 模板中的字典

python - Cqlengine查询: how to return dictionary?

python - 如何在flask数据表(服务器端)中实现sqlalchemy聚合函数?

python - 带有菜单栏的 Kivy