从查询集 Django 访问多对多字段
Access many to many field from queryset Django
我有两个模型:
class Vineyard(models.Model):
name = models.CharField(max_length=255, blank=True)
def __str__(self):
return self.name
class WineRegion(models.Model):
name = models.CharField(max_length=255)
vineyards = models.ManyToManyField(Vineyard, blank=True)
def __str__(self):
return self.name
我想访问葡萄酒产区的所有葡萄园。这是我尝试过的:
if len(id_list) > 0:
wr = WineRegion.objects.filter(id__in=id_list)
vineyardList = wr.vineyards.all()
但是它给了我一个错误---> AttributeError: 'QuerySet' object has no attribute 'vineyards'
我该如何解决这个问题?
编辑:
如果我有另一个名为 Country 的模型怎么办?这是模型:
class Country(models.Model):
name = models.CharField(max_length=255)
wine_rg = models.ManyToManyField(WineRegion, blank=True)
def __str__(self):
return self.name
我想访问葡萄酒产区的所有葡萄园,但现在我有一个国家/地区 ID 列表。我该如何解决?
我可以这样做:
wine_region_id = Country.objects.filter(id__in=country).distinct().values('wine_rg')
vineyardList = vineyardList.filter(wineregion__in=wine_region_id)
但是我很好奇有没有更好的方法来做这样的事情?
由于 wr
是 WineRegions
的列表,您需要先遍历它们:
vineyardList = []
for wr in WineRegion.objects.filter(id__in=id_list):
for vineyard in wr.vineyards.all():
vineyardList.append(vineyard)
但这会多次访问您的数据库以获取每个葡萄园对象。相反,您可以从 Vineyard
访问相关名称 wineregion
以在一个查询中获取所有葡萄园对象,如下所示:
vineyardList = Vineyard.objects.filter(wineregion__in=WineRegion.objects.filter(id__in=id_list))
或者简单地说:
vineyardList = Vineyard.objects.filter(wineregion__in=id_list)
我有两个模型:
class Vineyard(models.Model):
name = models.CharField(max_length=255, blank=True)
def __str__(self):
return self.name
class WineRegion(models.Model):
name = models.CharField(max_length=255)
vineyards = models.ManyToManyField(Vineyard, blank=True)
def __str__(self):
return self.name
我想访问葡萄酒产区的所有葡萄园。这是我尝试过的:
if len(id_list) > 0:
wr = WineRegion.objects.filter(id__in=id_list)
vineyardList = wr.vineyards.all()
但是它给了我一个错误---> AttributeError: 'QuerySet' object has no attribute 'vineyards'
我该如何解决这个问题?
编辑:
如果我有另一个名为 Country 的模型怎么办?这是模型:
class Country(models.Model):
name = models.CharField(max_length=255)
wine_rg = models.ManyToManyField(WineRegion, blank=True)
def __str__(self):
return self.name
我想访问葡萄酒产区的所有葡萄园,但现在我有一个国家/地区 ID 列表。我该如何解决?
我可以这样做:
wine_region_id = Country.objects.filter(id__in=country).distinct().values('wine_rg')
vineyardList = vineyardList.filter(wineregion__in=wine_region_id)
但是我很好奇有没有更好的方法来做这样的事情?
由于 wr
是 WineRegions
的列表,您需要先遍历它们:
vineyardList = []
for wr in WineRegion.objects.filter(id__in=id_list):
for vineyard in wr.vineyards.all():
vineyardList.append(vineyard)
但这会多次访问您的数据库以获取每个葡萄园对象。相反,您可以从 Vineyard
访问相关名称 wineregion
以在一个查询中获取所有葡萄园对象,如下所示:
vineyardList = Vineyard.objects.filter(wineregion__in=WineRegion.objects.filter(id__in=id_list))
或者简单地说:
vineyardList = Vineyard.objects.filter(wineregion__in=id_list)