【问题标题】:Querying objects in a View in DJANGO在 DJANGO 的视图中查询对象
【发布时间】:2011-03-22 19:41:38
【问题描述】:

我有一个名为destination 的django 模型。我有另一个模型,叫做 tours。旅游由目的地和其他元素组成。在我的目的地视图中,我希望有一个可用的旅游列表,其中包含与特定目的地相关的所有旅游。我不知道怎么写出来。这就是我所拥有的:

from django.template import Context, loader
from ceibelize.destinations.models import Destination
from ceibelize.tours.models import Tour
from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404

def detail(request, destination_id):
    dest_object = get_object_or_404(Destination, pk=destination_id) *****
    tours_in = get_object_or_404(Tour, Tour.destination=destination_id)
    t = loader.get_template('destinations/detail.html')
    c = Context({
        'dest_object':dest_object,
    })
    return HttpResponse(t.render(c))

* 是我试图弄清楚如何查询 Tour 对象的地方。旅游和目的地具有多对多的关系。

【问题讨论】:

    标签: python django-models django-templates django-views


    【解决方案1】:

    get_object_or_404() 只会得到一个对象。改为过滤。

    tours_in = Tour.objects.filter(destination=destination_id)
    

    【讨论】:

    • 谢谢! :) 聪明小子! :D
    猜你喜欢
    • 2015-11-04
    • 2016-10-05
    • 1970-01-01
    • 2020-07-06
    • 2012-02-21
    • 2021-10-21
    • 2016-10-27
    • 1970-01-01
    • 2014-02-06
    相关资源
    最近更新 更多