0

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.

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.