![](/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.