title: How to limit the queryset of related fields of serializer based on some request parameters in Django Rest Framework
body: <p>I have three models <code>Transaction</code>, <code>Business</code>, and <code>Location</code>. They are defined as follows:</p>
  
  <pre><code>class Business(models.Model): 
      # Can have zero or more locations. A user can have many businesses.
      name  = models.CharField(max_length=200, validators=[MinLengthValidator(1)])
      # ... and some other fields ...
  
  class Location(models.Model): 
      # Must have one business. Locations cannot exist without a business
      suburb   = models.CharField(max_length=150, validators=[MinLengthValidator(1)])
      business = models.ForeignKey(Business, related_name='locations')
      # ... and some other fields ...
  
  class Transaction(models.Model): 
      # Can have zero or one business
      # Can have zero or one location and the location must belong to the business. If business is empty, location must be empty
      business = models.ForeignKey(Business, on_delete=models.SET_NULL, null=True, blank=True, related_name='transactions')
      location = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True, blank=True, related_name='transactions')
      # ... and some other fields ...
  </code></pre>
  
  <p>And the serializers:</p>
  
  <pre><code>class BusinessRelatedField(serializers.PrimaryKeyRelatedField):
  
      def get_queryset(self):
          owner = get_owner_from_context(self.context)
          return Business.objects.filter(owner=owner)
  
  class LocationRelatedField(serializers.PrimaryKeyRelatedField):
  
      def get_queryset(self):
          params = self.context['request'].query_params
          business_params = params.get('business')
          if business_params is not None:
              owner = get_owner_from_context(self.context)
              return Location.objects.filter(owner=owner, business=business_params)
          else:
              return None
  
  class TransactionSerializer(serializers.ModelSerializer):
  
      business = BusinessRelatedField(required=False, allow_null=True)
      location = LocationRelatedField(required=False, allow_null=True)
  </code></pre>
  
  <p>The problem I was facing was that I didn't know how to restrict the value of <code>Location</code> based on the value of <code>Business</code>. I was manually performing this check inside <code>TransactionSerializer</code>'s <code>validate</code> method until it occurred to me to create a <code>PrimaryKeyRelatedField</code> subclass and override the <code>get_queryset</code> method. This seemed like a better approach to me (and it's actually working) but I'd like to know if this is the 'normal' way of doing it.</p>
  
  <p>The other problem I'm now facing is that the 'browsable API' no longer shows any choices for <code>Location</code> which I feel is a hint that I might be doing something wrong.</p>
  
  <p>Any help would be appreciated.</p>