Skip to content

Instantly share code, notes, and snippets.

@kevin-brown
Last active August 7, 2017 15:25
Show Gist options
  • Save kevin-brown/259f20cadb62be9ab2d8 to your computer and use it in GitHub Desktop.
Save kevin-brown/259f20cadb62be9ab2d8 to your computer and use it in GitHub Desktop.
Demonstration of how you can dynamically filter the queryset containing the objects which are allowed to be set on a field.
class FooSerializer(serializers.ModelSerializer):
# Any subclass of a RelatedField, which would normally have a queryset
bar = serializers.HyperlinkedRelatedField(
queryset=Bar.objects.none(), # don't unintentionally expose information
)
def __init__(self, *args, **kwargs):
# Make sure that self.fields is populated
super().__init__(*args, **kwargs)
# Get some extra parameter, usually either from the request or the view
baz_id = self.context["view"].kwargs["baz_id"]
# Generate the new, filtered queryset based on this extra value
bar_queryset = Bar.objects.filter(baz=baz_id)
# Update the queryset of objectd accepted by the field
self.fields["bar"].queryset = bar_queryset
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment