【发布时间】:2016-07-12 06:03:15
【问题描述】:
我正在努力为我的项目获取正确的查询。这是我的模型的一个例子:
from django.db import models
class Brand(models.Model):
name = models.CharField(max_length=30)
handle = models.SlugField(max_length=30, unique=True, null=True, blank=True)
def __unicode__(self):
return self.name
class Product(models.Model):
product_id = models.SlugField(unique=True)
brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, blank=True, null=True)
collections = models.ManyToManyField('Collection')
def __unicode__(self):
return self.product_id
我正在尝试根据Product.collection 的值获取所有Brand_name
例如:鞋子是Product.collection,我想得到所有Brand_name 和collection - 鞋子
我也试过__ 方法。不知何故,它不起作用。
【问题讨论】:
-
什么是
'Collection'?如果你有一个模型Collection说有一个属性type(CharField),那么你可以将多对多字段声明为collections = models.ManyToManyField(Collection),你可以过滤所有shoes(假设鞋子是由Collection.type == 'shoe') 通过shoes = collections.filter(type='shoe')识别。或者有Collection和Brand并且您希望Brand.name == 'shoe'成为True?你的问题不是很清楚。
标签: python django django-models foreign-keys many-to-many