跨越ForeignKey的dict中的Django queryset dict

时间:2015-07-06 12:15:49

标签: python django

我有点像Django / Python Noob,我正在努力解决一些我认为相对简单的问题。

我有两种模式:

class Place(models.Model):
    place_name = models.CharField(max_length=200)
    place_summary = models.TextField(max_length=1500, blank=True, null=True)
    ...

    def __unicode__(self):
        return self.place_name

class Place_Image(models.Model):
    place_name = models.ForeignKey(Place)
    place_image = models.CharField(max_length=100, null=True, blank=True)
    ...

    def __unicode__(self):
        return self.place_image_title

我想查询db并返回类似于:

的行
place_name_A, place_summary_A,  place_image {place_image_A1}
place_name_B, place_summary_B,  place_image {place_image_B1, place_image_B2}

我玩了几件事:prefetch_related,select_related,我摆弄了我的模型似乎不起作用。我相信答案是相当直接的,但我现在看不到它。一些帮助会很棒!

我应该处理这个模型(使用某种方法)还是在视图中(使用预取或其他东西)?

由于

更新: 我将在模板中使用数据,大致如下:

{% for place in places %}
    <ul>
        {{ place.place_name }}
        {{ place.place_summary }}
        # I then have an image carousel that displays images eg. '/static/images/{{ place.place_image_title}
    </ul>
{% endfor %}

3 个答案:

答案 0 :(得分:1)

如果您希望在视图级别执行此操作,则无需创建与表格完全相同的对象。关于ORM的好处是你可以导航&#39;通过它来获取您想要和需要的数据。因此,在您的情况下,您只需查询file.o: other_file.h $(CC) $(CFLAGS) $(CPPFLAGS) -c file.c -o ./$(OBJ_FILES)/$@ 模型,即可提取所需的数据。你可以这样做:

view.py

Place

template.html

def my_view(request):
    object_list = Place.objects.all()
    return render(request, 'template.html', {'object_list':object_list})

虽然您可以改进此代码,但是首先要担心掌握基础知识。

帮助改进代码和使用查询集的一些附注。

在模型中,您不需要为属性添加模型名称前缀。只需执行以下操作即可:

<table>
{% for item in object_list %}
    <tr>
        <td>{{ item.place_name }}</td>
        <td>{{ item.place_summary }}</td>
        <td>
            <ul>
            {% for pic in item.place_image %}
                <li>{{ pic.place_name }}</li>
            {% endfor %}
            </ul>
        </td>
    </tr>
{% endfor %}
</table>

答案 1 :(得分:0)

根据理解,我认为这是要走的路:

Place.objects.all().values('place_name','place_summary','place_image')

看到它解决了你的目的?

答案 2 :(得分:0)

我猜您可以从Place实例访问Place_Image查询集,如下所示:

place.place_image_set.all() # to retrieve all 

因为django将'_set'添加到字段名称以获得反向关系。您可以通过使用related_name指定其他字段名称来更改它:

place_name = models.ForeignKey(Place, related_name='place_images') 
相关问题