我有一个问题 看下面:
我有这个型号:
class Shoes(models.Model):
shop = models.ForeignKey(Store, related_name="%(class)s")
name = models.ForeignKey(ShoesItem)
size = models.ManyToManyField(ShoesSize, help_text=_("Get useful sizes"))
price = models.IntegerField()
在我的情况下,我有模特ShoesSize用于存储所有ShoesSize和ShoesItem用于存储此商品
如何从ShoesItem实例中获取所有尺码和所有商店? 有(例如,不完整):
class Store(models.Model):
name = models.CharField(max_length=255)
class Item(models.Model):
name = models.CharField(max_length=255)
brand = models.ForeignKey(Brand, related_name="%(app_label)s_%(class)s")
sysname = models.SlugField(max_length=255)
has_shop = models.BooleanField(editable=False, default=False)
description = models.TextField(blank=True, verbose_name="Описание")
color = models.ManyToManyField(Color, blank=True, related_name='%(app_label)s_%(class)s')
我获得了Item模型的实例列表。在那之后,我想获得所有类型的物品的所有尺寸和商店
答案 0 :(得分:1)
使用型号名称使用反向查询。
获取鞋子项目:
shoes_item = ShoesItem.objects.all()[0]
通过Shoes对象获取ShoesItem的ShoesSize对象:
sizes = ShoesSize.objects.filter(shoes__name=shoes_item)
通过Shoes对象获取ShoesItem的Store对象:
shops = Store.objects.filter(shoes__name=shoes_item)
了解详情 - Lookups that span relationships
对于ShoesItem的查询集:
shoes_items = ShoesItem.objects.filter(has_shop=True)
sizes = ShoesSize.objects.filter(shoes__name__in=shoes_items)
shops = Store.objects.filter(shoes__name__in=shoes_items)