I'm new to DRF and have just started building an API.
I've a model called Shop. And I've two user different user types : Customer and Supplier.
Considering constraints above, how should I add the custom field to the response of the request? What's the best way to do this ?
The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.
Django get POST data as dictWhen you submit data or parameters through a POST request to a Django application, these parameters are stored in the form of a dictionary-like object of the class QueryDict. This object is a dictionary-like object i.e. you can use almost all the functions of a dictionary object.
queryset - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set read_only=True . many - If applied to a to-many relationship, you should set this argument to True .
You can define a distance
SerializerMethodField
, and there access the current user location using serializer's context
. Then compute distance using current user location and shop's location.
class ShopSerializer(serializers.ModelSerializer):
distance = serializers.SerializerMethodField()
class Meta:
model = Shop
fields = (.., 'distance')
def get_distance(self, obj):
current_user = self.context['request'].user # access current user
user_location = current_user.location
distance = <compute distance using obj.location and user_location>
return distance
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With