![](/img/trans.png)
[英]Retrieve nested dict from Django nested queryset with ForeignKey?
[英]Django queryset dict in dict across ForeignKey
我有点像 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
我想查询数据库并返回如下所示的行:
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 %}
如果您希望在视图级别执行此操作,则无需创建与表完全相同的对象。 ORM 的优点在于您可以通过它“导航”以获取您想要和需要的数据。 因此,在您的情况下,您只需要查询Place
模型即可提取出您需要的数据。 你可以这样做:
查看.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
根据理解,我认为这是要走的路:
Place.objects.all().values('place_name','place_summary','place_image')
看看它解决了你的目的?
我猜你可以从这样的 Place 实例访问 Place_Image 查询集:
place.place_image_set.all() # to retrieve all
因为 django 将 '_set' 添加到反向关系的字段名称。 您可以通过specifiying不同的字段名称更改related_name
是这样的:
place_name = models.ForeignKey(Place, related_name='place_images')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.