Create a queryset that automatically queries onetoone objects

I'm building a django application that has a model with multiple OneToOne relationships:

class MyApp(BaseModel):
    site_1 = models.OneToOneField(
        Site, on_delete=models.CASCADE, related_name="site1", null=True
    )
    site_2 = models.OneToOneField(
        Site, on_delete=models.CASCADE, related_name="site2", null=True
    )
    site_3 = models.OneToOneField(
        Site, on_delete=models.CASCADE, related_name="site3", null=True
    )

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = "Main Application"
        verbose_name_plural = "Main Application"

When I create a queryset using MyApp.objects.all() it returns an object with just the primary keys:

    {
    "model": "mesoamerica.mesoamericaapp",
    "pk": 1,
    "fields": {
      "site_1": 1,
      "site_2": 2,
      "site_3": 3
    }

However, I'd like to create a queryset that grabs each of the Site models by pk and attaches them to the query, rather than having to do that myself. Is there a queryset that will do this?

You can do this:

def my_app_data(request):
queryset = MyApp.objects.prefetch_related('site1', 'site2', 'site3').all()

# Serialize queryset to JSON
data = serialize('json', queryset)

# Return JSON response
return JsonResponse(data, safe=False)

but if you wanna write serializer classes for your site and myapp model, check document: https://www.django-rest-framework.org/tutorial/1-serialization/

Back to Top