使用外键注释结果

时间:2013-08-07 13:32:14

标签: django django-queryset

我想在Django中过滤一个对象,并将其与结果为ForeignKey的任何对象一起返回。我不确定注释是否是我需要的东西,或其他东西。

这是我的模特:

class Dress(models.Model):
  name = models.CharField(...)
  price = models.FloatField(...)

class ClothingSize(models.Model):
   code = models.CharField(...)

class DressSizeAvailable(models.Model):
  dress = models.ForeignKey(Dress)
  size = models.ForeignKey(ClothingSize)

假设我想过滤掉50美元以下的所有连衣裙,然后用可用的尺码显示它们。这样做的最佳方式是什么?

我已经达到了这个目标:

# In view
results = Dress.objects.filter(price__lt=50)
# How to annotate with available sizes?

# In template
{% for result in results %}
  {{ result.name }}, ${{ result.price }}
  Sizes: {{ ??? }}
{% endfor %}

2 个答案:

答案 0 :(得分:1)

### 1st solution (similar to Daniel Rosenthal's answer but with performances concern)
results = DressSizeAvailable.objects.filter(dress__price__lt=50).select_related('dress', 'size')
# then you can browse your DressSizeAvailables as you wish in your template. The select related allows you NOT TO query the database again when you generate your template

### 2nd solution
results = Dress.objects.filter(price__lt=50).prefetch_related('dresssizeavailable_set__dress')

{% for dress in results  %}
    {{ dress.name }}, ${{ dress }}
    Sizes: <ul>
        {% for dsa in dress.dresssizeavailable_set %}
            <!-- Thanks to the prefetch_related, we do not query the base again here -->
            <li>{{ dsa.size.code }}</li>
        {% endfor %}
    </ul>
{% endfor %}

答案 1 :(得分:0)

您需要为模板提供DressSizeAvailable个对象的查询集(或类似内容)。首先,您需要获取您感兴趣的所有Dress个对象,然后根据这些礼服过滤DressSizeAvailable

所以在你看来:

dresses = Dress.objects.filter(price__lt=50)
dress_size_available = []
for dress in dresses:
    available = DressSizeAvailable.objects.filter(dress=dress)
    dress_size_available.append(available)

然后渲染模板,将变量dress_size_available

传递给它

您的模板可以非常简单。

{% for dsa in dress_size_available %}
    {{ dsa.dress.name }}, ${{ dsa.dress.price }}
    Size: {{ dsa.size }}
{% endfor %}