Skip to main content
 首页 » 编程设计

python之Django queryset dict in dict 跨 ForeignKey

2024年10月24日40mq0036

我是一个 Django/Python 新手,正在为一些我认为相对简单的事情而苦苦挣扎。

我有两个模型:

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 

我想查询数据库并返回类似于以下内容的行:

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,我摆弄了我的模型,但似乎不起作用。我敢肯定答案是相当直截了当的,但我现在看不到。一些帮助会很棒!

我应该在模型中(使用某种方法)还是在 View 中(使用预取或其他方法)处理它?<​​/p>

谢谢

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

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

请您参考如下方法:

如果您希望在 View 级别执行此操作,则无需创建与表完全相同的对象。 ORM 的伟大之处在于您可以“导航”它以获取您想要和需要的数据。因此,在您的情况下,您只需要查询 Place 模型即可提取所需的数据。你可以这样做:

View .py

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

模板.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> 

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


只是一些有助于改进代码和使用查询集的旁注。

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

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