简体   繁体   English

Django queryset dict in dict 跨外键

[英]Django queryset dict in dict across ForeignKey

I'm a bit of a Django/Python Noob and am struggling with something that I imagine is relatively simple.我有点像 Django/Python Noob,并且正在为我认为相对简单的东西而苦苦挣扎。

I have two models:我有两个模型:

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

I want to query the db and returns rows that looks something like:我想查询数据库并返回如下所示的行:

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}

I played around with a few things: prefetch_related, select_related, I fiddled with my model that didn't seem to work.我玩了一些东西:prefetch_related,select_related,我摆弄了似乎不起作用的模型。 I'm sure the answer is fairly straight forward, but I can't see it at the moment.我确信答案是相当直接的,但我目前看不到。 Some help would be great!一些帮助会很棒!

Should I be handling this is the model (with some sort of method) or in the view (with prefetch or something else)?我应该处理这是模型(使用某种方法)还是在视图中(使用预取或其他方式)?

Thanks谢谢

UPDATE: I'm going to use the data in a template, roughly like this:更新:我将在模板中使用数据,大致如下:

{% 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 %}

If you are looking to do this at the view level there is no need to create an object which is exactly like a table.如果您希望在视图级别执行此操作,则无需创建与表完全相同的对象。 The great thing about the ORM is you can 'navigate' through it to get the data you want and need. ORM 的优点在于您可以通过它“导航”以获取您想要和需要的数据。 So in your case you only need to query the Place model pulling out the data you need.因此,在您的情况下,您只需要查询Place模型即可提取出您需要的数据。 You can do something like this:你可以这样做:

view.py查看.py

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

template.html模板.html

<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>

Whilst you can improve this code just worry about getting to grips with the basics first.虽然您可以改进此代码,但只需担心首先掌握基础知识。


Just some side notes to help improve your code and working with querysets.只是一些旁注来帮助改进您的代码和使用查询集。

In your models you do not need to prefix attributes with the model name.在您的模型中,您不需要在属性前加上模型名称。 Just doing the following is fine:只需执行以下操作即可:

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

    def __unicode__(self):
        return self.name

As per the understanding I think this is the way to go:根据理解,我认为这是要走的路:

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

and see it solves your purpose?看看它解决了你的目的?

I guess you can access the Place_Image queryset from a Place instance like this:我猜你可以从这样的 Place 实例访问 Place_Image 查询集:

place.place_image_set.all() # to retrieve all 

since django adds '_set' to the field name for reverse relationship.因为 django 将 '_set' 添加到反向关系的字段名称。 You can change it by specifiying a different field name with related_name like this:您可以通过specifiying不同的字段名称更改related_name是这样的:

place_name = models.ForeignKey(Place, related_name='place_images') 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM