Home > front end >  How to get a QuerySet with type of a ForeignKey attribute in Django
How to get a QuerySet with type of a ForeignKey attribute in Django

Time:08-20

I have a simple database model in Django that looks like:

class Employee(Model):
    first_name = models.CharField(max_length=128)
    last_name = models.CharField(max_length=128)

class PrizeDraw(Model):
    winner = models.ForeignKey(
        Employee,
        null=True,
        on_delete=models.SET_NULL,
    )

What I want now is a QuerySet of type Employee that contains all the winners of all PrizeDraws. I would have thought that to be fairly straightforward by something something like:

def get_queryset(self):
    return PrizeDraw.objects.exclude(winner__isnull=True).values('winner')

However, that doesn't actually return me what I want, instead it returns:

<QuerySet [{'winner': (Employee1) }, {'winner': (Employee2) }, etc...]>

Which makes sense according to the values() documentation it returns a Dictionary of values. But this doesn't work for me in the rest of the code I need, so I want to select only the second (i.e. value) part of the key-value pair and return that as a QuerySet that just looks like <QuerySet[Employee1, Employee2, etc...]>.

How can I select the right value as to get that desired QuerySet?

CodePudding user response:

You can filter with:

Employee.objects.filter(prizedraw__isnull=False).distinct()

This will retrieve the Employees for which there is at least one related PrizeDraw record.

  • Related