fpaekoaij
fpaekoaij

Reputation: 193

django query accessing foreign key data

Apology if this is a duplicate but I could not find any satisfying answer for this case. Maybe I am doing something fundamentally wrong, like need to define models in a different way.I am also very new to django.So suggestions will be really helpful.

Suppose I have my models like this:

from django.contrib.auth.models import Group
class Team(Group):
    description = models.CharField(max_length=30)

class Players(models.Model):
    name = models.CharField(max_length=60)
    team = models.ForeignKey(Team, on_delete=models.CASCADE)

Now if I for example, want a queryset of all players by the Team model what can I do? I have the foreign key in the Players model and not in Team model. So something like Team.objects.filter(logic) is needed to get all players. But exactly what logic will work here?

Any help will be much appreciated.

Upvotes: 0

Views: 1995

Answers (2)

Naqib Hakimi
Naqib Hakimi

Reputation: 912

Django ORM also can filter by relation. these kind of filtering is valid for all kind of relations.

 players = Players.objects.filter(team__id = 1)

in case you have the team object.

players = Players.objects.filter(team = team)

Upvotes: 3

neverwalkaloner
neverwalkaloner

Reputation: 47354

Django allows you get access to related objects in reverse way. It calling reverse relation. And related manager objects using for it. You can find more details here and here. In your specifc case you can get players using players_set team's attribute:

team = Team.objects.get(pk=1)
players = team.players_set.all()

Upvotes: 2

Related Questions