Question

Models

class Beer(models.Model):
    pass

class Salas(models.Model):
    name =  models.CharField(max_length=20)
    beers =     models.ManyToManyField('Beer', blank=True)

View

beer = Beer.objects.get(user=user)
id_sala = request.GET['id_sala']
sala = get_object_or_404(Salas, id=id_sala)


if beer.salas_set.filter(nombre=sala):
# if beer.objects.filter(sitios__id=beer).exists():
    sala.beers.remove(beer)

else:
    sala.beers.add(beer)

I want to see if there is relationship of beer with sala, how to make this??

Was it helpful?

Solution 2

With your solution there might be a problem since name of salas is not unique. So, if you filter by the name of the sala expecting to find one and only one sala, that might not happen.

I advice you to do:

if sala in beer.salas_set.all():
    #do stuff:
else:
    # do other stuff

that way, beer.salas_set.all() will return a QuerySet in which you can check if a specific object is there with the 'in' keyword.

UPDATE: as noted in the comments, you might not want to use .all() since it's expensive. Use .exists() instead. Thanks to @illagrenan

OTHER TIPS

I advise you to use:

if beer.salas_set.filter(pk=sala.pk).exists():
    # do stuff

If you use sala in beer.salas_set.all() instead, it selects all records from the relation table and loops over them to find, whether the given object is there or not. However, beer.salas_set.filter(pk=sala.pk).exists() only selects zero or one row from the database and immediately gives the result (without looping).

Django 4.0 has added a new contains() method to QuerySets, which is a natural fit for this use-case.

if beer.salas_set.contains(sala):
    # do stuff
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top