我定义了三个模型,如下所示
class City(models.Model):
city_name = models.CharField(...)
class Restaurant(models.Model):
restaurant_name = models.CharField(...)
city = models.ManyToManyFields(City)
class MenuItemCount(models.Model):
restaurant = models.ForeignKey(Restaurant)
city = models.ForeignKey(City)
menu_count = models.IntegerField()需要注意的是,并不是所有的餐馆和城市都存在于MenuCount中。所以需要一个左连接。
我正在尝试编写django查询来检索餐厅名称、城市名称和菜单计数的列表。示例结果如下
restaurant1, city1, 20
restaurant1, city2, None
restaurant2, city2, 30
restaurant3, city1, None我该如何为此编写一个查询呢?
发布于 2015-02-22 22:34:59
如果你想在一个查询中获得所有数据,你可以使用prefetch_related。您可以查看文档here。下面是一个示例。
City.objects.prefetch_related('restaurant_set', 'menuitemcount_set').all()https://stackoverflow.com/questions/28629338
复制相似问题