【问题标题】:How to get into details view from another details view and get all the queryset in template properly?如何从另一个详细信息视图进入详细信息视图并正确获取模板中的所有查询集?
【发布时间】:2019-06-28 11:36:57
【问题描述】:

我需要从另一个详细信息视图进入详细信息视图..但我无法清楚地传递查询集...

在模型中:

class Match(models.Model):
    mega_league = models.ManyToManyField('MegaLeague', blank=True)


class MegaPricePoolBreak(models.Model):
    pass


class MegaLeague(models.Model):
    price_pool_break = models.ManyToManyField(MegaPricePoolBreak, blank=True)

在视图中:

def league(request):
    match = Match.objects.all()
    context = {
        'match': match,
    }
    return render(request, 'main/league.html', context=context)


def league_detail(request, pk):
    match = get_object_or_404(Match, pk=pk)
    context = {
        'match': match,
    }
    return render(request, 'main/league_detail.html', context=context)


def league_detail_more(request, pk):
    match = get_object_or_404(Match, pk=pk)
    context = {
        'match': match,
        'title': 'select matches',
    }
    return render(request, 'main/league_detail_more.html', context=context)

league 模板中,我通过{% url 'league_detail' match.pk %} 将查询集从Match 获取到league_detail 模板中,在league_detail 模板中我通过{% url 'league_detail_more' match.pk %}---这是主要问题..它传递了 Match 的所有 pk,但我需要传递 match.pk 和 match.mega_league.pk 以将查询集从 Match 获取到 league_detail_more 模板..

在所有模板中,我使用for 循环..它正在工作...但是要获取特定的 pk 查询不起作用..

它适用于league_detail 模板,但不适用于league_detail_more 模板..in league_detail_more 来自league_detail 的模板pk pass 不起作用。

如何使用match = get_object_or_404(Match, pk=pk) 清楚地获取两个模板的所有查询集??

【问题讨论】:

  • 对不起,您的问题再次不清楚。什么“特定的 pk 查询”不起作用?您究竟看到了什么,这与您想要的有什么不同?
  • 先生,看看模型,在Match 中有manytomany 字段MegaLeagueMegaLeague 也有manytomany 字段MegaPricePoolBreak... 所以,在league_detail 模板中我使用@ 987654342@ 获取mega_league 查询和league_detail_more 模板我也使用{% for mega_league in match.mega_league.all %} 获取mega_league 查询...但在这个模板中我只需要一个查询集...不想使用for 循环但是也想访问Match查询数据...
  • 在视图中我可以使用这个mega = get_object_or_404(MegaLeague, pk=pk) 然后我可以使用mega.match_set 获取Match 查询集...但是我可以找到Match 的所有查询集..因为它是MegaLeague 的manytomany 字段...我需要一个使用pk 的查询集
  • 一句话,我需要为Match queryset 和MegaLeague queryset 在这个{% url 'league_detail_more' match.pk %} url 中一次传递两个pk ......这怎么可能@DanielRoseman 先生跨度>

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


【解决方案1】:

我还是不太明白你的问题在哪里。

如果您只想将两个 ID 传递给一个 URL,那很简单:

path('league_detail_more/<int:match_id>/<int:league_id>/', league_detail_more, name='league_detail_more')

在视图中:

def league_detail_more(request, match_id, league_id):
    match = get_object_or_404(Match, pk=match_id)
    league = get_object_or_404(MegaLeague, pk=league_id)

【讨论】:

  • 那么{% url 'league_detail_more' match.pk %} 将传递两个 ID
  • 当然,您可以通过传递两个 ID 来做到这一点:{% url 'league_detail_more' match.pk league.pk %} 或任何联赛变量。
猜你喜欢
  • 1970-01-01
  • 2010-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-15
相关资源
最近更新 更多