pythondjangodjango-rest-frameworkdjango-urls

can I use the slug from a different urls.py file?


I'm trying to access a slug field from a different urls.py file, and I'm getting this error

FieldError at /new-api/tournaments/fifa-world-cup/teams/
Unsupported lookup 'custom_url' for ForeignKey or join on the field not permitted.

I'm wondering if the reason I'm getting this error is because you cant do that or if it's another reason

I have 2 files for urls, one includes the other in it,

urls.py (tournament)

urlpatterns = [
    path("", views.getNewTournaments, name="tournaments"),
    path("<slug:custom_url>/", views.getNewTournament, name="tournament"),
    path("create/", views.postNewTournament, name="post-tournament"),
    path("<slug:custom_url>/teams/", include("teams.urls"), name="tournament-teams"),
]

urls.py (teams)

urlpatterns = [
    path("", views.teams.as_view(), name="teams"),
]

Here are the views.py files

views.py (tournaments)

@api_view(["GET"])
def getNewTournaments(request):
    tournaments = NewTournament.objects.all()
    serializer = NewTournamentSerializer(tournaments, many=True)
    return Response(serializer.data)

views.py (teams)

class teams(APIView):
    def get(self, request, custom_url):
        teams = Team.objects.filter(tournament__custom_url=custom_url)
        serializer = TeamSerializer(teams, many=True)
        return Response(serializer.data)

Solution

  • So I realized that my error was my model for the teams had the past model version of the tournaments

    Old

    class Team(models.Model):
        tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE)
    

    New

    class Team(models.Model):
        tournament = models.ForeignKey(NewTournament, on_delete=models.CASCADE)