How to check if an object exists in many

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 a connection between beer and lard, how to do it?

+4
source share
2 answers

There may be a problem with your solution, as the name of the bacon is not unique. So, if you filter out the name of the sala, expecting to find one and only one sala, this may not happen.

I advise you to do:

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

this beer.salas_set.all()will return a QuerySet in which you can check if a particular object exists with the keyword "in".

+6
source

I advise you to use:

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

sala in beer.salas_set.all() , , , . beer.salas_set.filter(pk=sala.pk).exists() ( ).

+12

Source: https://habr.com/ru/post/1539035/


All Articles