返回此查询集中使用的所有外键

时间:2017-11-05 14:22:58

标签: django django-models django-forms

我正在努力解释我想做什么(因此我无法找到关于此的帖子)所以希望有人可以帮助我。

我有几个型号,所有型号都与产品型号相关联

class Product(models.Model):
    category = models.ManyToManyField(Category)
    collection = models.ForeignKey(Collection)
    item_type = models.ForeignKey(ItemType)
    colour = models.ManyToManyField(Colour)
    product_name = models.CharField(max_length = 250, default='')
    product_name_pl = models.CharField(max_length = 250, default='')
    last_updated = models.DateTimeField(auto_now_add=False, auto_now=True)
    active = models.BooleanField(default=True)
    product_comment = models.CharField(max_length = 300, default='', blank=True)
    product_comment_pl = models.CharField(max_length = 300, default='', blank=True)
    display_order = models.PositiveIntegerField(blank=True)

    def __str__(self):
    return self.product_name

e.g。

class Collection(models.Model):
    collection_name = models.CharField(max_length = 250)
    slug = models.SlugField(unique=True, default='m')
    description = models.TextField(blank=True)
    image = models.FileField(upload_to='images/collections/', blank=True)
    collection_type = models.ManyToManyField(CollectionType)
    display_order = models.PositiveIntegerField(default=999)

    def __str__(self):
    return self.collection_name

class Colour(models.Model):
    colour_name = models.CharField(max_length = 250)
    slug = models.SlugField(unique=True, default='m')
    description = models.TextField(blank=True)
    image = models.FileField(upload_to='images/types/', blank=True)
    def __str__(self):
    return self.colour_name

我的想法是,当我使用Collection检索一组产品时,我想要在当前选择中列出可用颜色的列表,并且可能计算每种颜色的每种产品的数量。

我最常寻找的是在查询集文档中找到正确方向的一点,如果可以做到的话,不要期望完整的解决方案!

1 个答案:

答案 0 :(得分:0)

如果您有收藏品,则可以通过相关名称访问收藏中的产品:

class Product(models.Model):
    colour = models.ManyToManyField(Colour)
    collection = models.ForeignKey(Collection, related_name = 'products)

然后您从Colletion:

获得访问颜色
collection = Collection.object.all.first()

for product in collection.products:
    print(product.colour) # print product colors queryset. You can convert it to list if required.
    print(product.colour.count()) # how many colors you have 

P.S。更好地将颜色重命名为Product中的颜色。更容易理解它是复数。