Django manytomany querying showing none and/or unsuccessful

1.4k views Asked by At

I am having trouble querying a list of items in a many to many relationship. The model I am trying to query is below. This is a model that will indicate a worker selecting an "opening" and many workers can select the same "opening". I am trying to select the list of workers that have selected an "opening" but I am not successful.

class FavOpening(models.Model):
    opening = models.OneToOneField(Openings, blank=True, default=None)
    worker = models.ManyToManyField(Worker, blank=True, default=None)

    def __unicode__(self):
        return str(self.opening)

It is very strange because I tried this below for the type of opening based on a chosen worker(id-31) and it works, the opening that the worker has selected will print.

employee = get_object_or_404(Worker, id=31)
print employee.favopening_set.all()

But when I do it the other way round to get the worker inside the manytomany using the below, it does not work. Says it does not have attribute "favopening_set"

openingobj = get_object_or_404(Openings, id=1)
print openingobj.favopening_set.all()

I also tried to do the below to get the list of workers based on the opening(id=1) but I am getting no result - showing Workers.Worker.None, which is not true because I have at least one worker the have selected this opening.(I checked in admin)

openingobj = get_object_or_404(Openings, id=1)
print openingobj.favopening.worker

Finally, I tried this below based on some research that says to use prefetch to get a set of things - What's the difference between select_related and prefetch_related in Django ORM?, but it says that the manager is not accessible via openings instances.

openingobj = get_object_or_404(Openings, id=1)
openingobj.objects.prefetch_related('favopening_set').all()
1

There are 1 answers

3
Alex Vyushkov On BEST ANSWER

Edited response to take into account feedback in the comment

So you want to get a queryset of all worker who has selected an opening. Is code below helpful?

  openingobj = get_object_or_404(Openings, id=1)
  workers_queryset = opening.favopening.worker.all()

It may be a good idea to rename "worker" to "worker", I think.