Getting the value of a foreign key of a foreign key in Django

I have three models as follows:

class ServiceCategory(models.Model):
    name = models.CharField(max_length=50)

    def natural_key(self):
        return self.name

class Service(models.Model):
    service_category = models.ForeignKey(ServiceCategory, on_delete=models.CASCADE)
    name = models.CharField(max_length=50)

    def natural_key(self):
        return self.name

class Request(models.Model):
    name = models.CharField(max_length=50)
    services = models.ManyToManyField(Service)

    def natural_key(self):
        return self.name

I want to query with the default Django in a way that I can get the names of the Service Category since I will be filtering on it.

Currently I have the following:

    data = Request.objects.all()

    data = serialize("json", data, use_natural_foreign_keys=True)

So far I only get back the names of the services, but not the service categories. I have tried values but it throws an error when I serialize. I tried to add the fields argument in serialize with services__service_category__name and it did not work as well.

Can anyone help with this please ?

Try it with the following code in your view, it works for me:

def get_categories(request):
    requests = Request.objects.all()
    service_categories = []
    for request in requests:
        service_categories = request.services.values("service_category__name").all()
Back to Top