访问Django中的外键对象

时间:2014-01-22 19:38:22

标签: django django-models

我有两种模式:

class Item(models.Model):
    name = models.CharField()
class Param(models.Model):
    product = models.ForeignKey(Item, related_name="param")
    height = models.IntegerField()
    price = models.IntegerField()
  1. 我想要的是以平均价格注释商品,但只保留高度的参数> 60。

    items = Item.objects.filter(param__height__gt=60).annotate(price=Avg('param__price'))
    
  2. 这就是我遇到问题的地方。我想从上面的查询中获取过滤的Param对象。 有可能吗? 我知道有解决方法:

    for item in items:
        item.params = item.param.filter(height__gt=60)   
    
  3. 但是还有很多其他问题。 那么,我的问题是我是否可以从项目中访问过滤的param对象?

2 个答案:

答案 0 :(得分:1)

class Artist():
    blah = models.TextField()


class Album()
    blah = models.ForeignKey(blah)

关键是要像这样^

在类中着色

另外,例如,键可以是x,y点,时间,用户或任何你想要的东西!

https://github.com/Ry10p/django-Plugis/blob/master/courses/models.py 示例第52行

-Cheers

答案 1 :(得分:0)

items = Item.objects.select_related('param').filter(param__height__gt=60).annotate(price=Avg('param__price')).all()
相关问题