Foobar
Foobar

Reputation: 931

Retrieving Unrelated Objects in Django REST Framework

My model consists of 3 classes: Offer, Application, and Contract. Relationships are as follows:

Application to Offer: One to One

Application to Contract: One to One

Model code is as follows:

class Application(models.Model):
   application_name = models.CharField(max_length=255)

class Offer(models.Model):
   offer_name = models.CharField(max_length=255)
   application = models.OneToOneField(Application)

class Contract(models.Model):
   contract_name = models.CharField(max_length=255)
   application = models.OneToOneField(Application)

Is there a way for me to access Contract from Offer via Application in a single REST call? I know how to access Application from Offer since they are related. A way around this is to relate Offer to Contract but I would prefer not to do this because it would not be considered good relational database design.

Any help would be greatly appreciated. Thanks.

Upvotes: 0

Views: 73

Answers (1)

p14z
p14z

Reputation: 1810

You should add a related_name to your relationships:

class Application(models.Model):
   application_name = models.CharField(max_length=255)

class Offer(models.Model):
   offer_name = models.CharField(max_length=255)
   application = models.OneToOneField(Application, related_name='offer')

class Contract(models.Model):
   contract_name = models.CharField(max_length=255)
   application = models.OneToOneField(Application, related_name='contract')

Your url should look like this:

path('offer/<int:pk>/contract/', ContractDetailView.as_view(), name='contract-detail'),
from rest_framework import exceptions
from rest_framework.generics import RetrieveAPIView


class ContractDetailView(RetrieveAPIView):
    serializer_class = ContractSerializer
    ...

    def get_object(self):
        try:
            offer = Offer.objects.get(pk=self.kwargs['pk'])
            return offer.application.contract
        except Offer.DoesNotExist:
            raise exceptions.NotFound('Offer not found.')

Upvotes: 1

Related Questions