URL路径中有2个子弹

时间:2019-07-09 12:41:50

标签: django django-views

我想要这样的网址

example.com/lol/tournament/tournament-slug/match/match-slug

但是,我这样做是正确的方法吗?有没有更好的办法?代码:leagueoflegendsgame=game[0]

views.py

def lolmatch_detail(request, tournamentslug, lolslug):
    lolmatch=get_object_or_404(LeagueOfLegendsGame, lol_slug=lolslug)
    game=LeagueOfLegendsGame.objects.filter(lol_slug=lolslug)
    tournamentslug = get_object_or_404(Tournament, tournament_slug=tournamentslug, leagueoflegendsgame=game[0])

urls.py

path('lol/tournament/<str:tournamentslug>/match/<str:lolslug>', lolmatch_detail, name='lol_match_detail'),

models.py

class LeagueOfLegendsGame(Game):
    name=models.CharField(max_length=255,blank=True,null=True)
    lol_slug=models.SlugField(unique=True,max_length=255)
    tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE, null=True, blank=True)
    match=models.ManyToManyField(Match)...

class Tournament(models.Model):
    name=models.CharField(max_length=255)
    tournament_slug=models.SlugField(unique=True,max_length=255)

1 个答案:

答案 0 :(得分:1)

您可以在单个查询中匹配两个子弹,例如:

def lolmatch_detail(request, tournamentslug, lolslug):
    game = get_object_or_404(
        LeagueOfLegendsGame,
        lol_slug=lolslug,
        tournament__tournament_slug=tournamentslug
    )
    # ...

此处数据库将创建一个JOIN,以查找带有LeagueOfLegendsGame的{​​{1}},并检查它是否指向具有给定lolslug的{​​{1}} ,并返回Tournament(如果存在)。