V
V
Vyacheslav2019-05-23 20:12:13
Django
Vyacheslav, 2019-05-23 20:12:13

How to get object from Many-To-Many Field?

I have models:

class Position(models.Model):
    name = models.CharField(max_length=50, unique=True, default=None, blank=False, null=False)

class Team(models.Model):
    city = models.ForeignKey(City, null=True, on_delete=models.DO_NOTHING)
    position = models.ForeignKey(Position, null=True, on_delete=models.CASCADE)

class Game(models.Model):
    gameId = models.IntegerField(default=0, blank=False, null=False)  # не id
    team = models.ManyToManyField(to=Team)

class City(models.Model):
    name = models.CharField(default=None, unique=True, max_length=50, blank=False, null=False)

GameId, Position_name and City_name are passed as arguments to the function.
I need queries or queries with code (if iterations over the QuerySet are needed):
1. to check if there is a Team object added to the m2m of the Game object and associated with Position (ForeignKey)
2. get this object
3. assign a City to it, if the current City does not match the function argument.
It is necessary to make a minimum number of requests.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FulTupFul, 2019-05-24
@ElefanObi

game = Game.objects.get(id=gameId)
team = game.team.filter(position__name=Position_name)
if team.exists():
    team[0].city = City.objects.get(name=City_name) # Тут стоит сделать более строгую проверку чтобы не было дублей
    team[0].save()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question