I have a model:
class Size(models.Model):
size = models.DecimalField(max_digits=5, decimal_places=1)
def plus_one(self):
self.size += 1
self.save()
And I have a simple serializer for this:
class SizeSerializer(serializers.ModelSerializer):
class Meta:
model = Size
fields = '__all__'
How can I call a plus_one model method from my view, using DRF?
How is it callable, what is good practice for that? Thanks!
Added:
class SizeAPIView(generics.UpdateAPIView):
serializer_class = SizeSerializer
queryset = Size.objects.filter()
If I understood you right you need to call plus_one each time when object updated. In this case you can override perform_update() method like this:
class SizeAPIView(generics.UpdateAPIView):
serializer_class = SizeSerializer
queryset = Size.objects.filter()
def perform_update(self, serializer):
serializer.save()
serializer.instance.plus_one()
This should be done on serializer level while your SizeAPIView remains unchanged:
class SizeSerializer(serializers.ModelSerializer):
class Meta:
model = Size
fields = '__all__'
def update(self, instance, validated_data):
for attr, value in validated_data.items():
setattr(instance, attr, value)
instance.plus_one() # performs `instance.save` too.
Documentation on saving instances.
Related
I have a modelset view in which different customs functions are defined based on the requirement. I have to write another get function in which I want to use the same serializer class. But the field which I have defined in the serializer class in pkfield but for the get function, I want it as a stringfield rather than pk field. How to achieve that??
Also, I have defined depth=1, which is also not working.
class Class(TimeStampAbstractModel):
teacher = models.ForeignKey(
Teacher,
on_delete=models.CASCADE,
null=True,
related_name="online_class",
)
subject = models.ForeignKey(
Subject,
on_delete=models.SET_NULL,
null= True,
related_name= "online_class",
)
students_in_class = models.ManyToManyField(Student, related_name="online_class")
My view:
class ClassView(viewsets.ModelViewSet):
queryset = Class.objects.all()
serializer_class = ClassSerializer
serializer_action_classes = {
'add_remove_students': AddStudentstoClassSerializer,
'get_all_students_of_a_class': AddStudentstoClassSerializer,
}
def get_serializer_class(self):
"""
returns a serializer class based on the action
that has been defined.
"""
try:
return self.serializer_action_classes[self.action]
except (KeyError, AttributeError):
return super(ClassView, self).get_serializer_class()
def add_remove_students(self, request, *args, **kwargs):
"""
serializer class used is AddStudentstoClassSerializer
"""
def get_all_students_of_a_class(self,request,pk=None):
"""
for this I function too, I want to use the same AddStudentstoClassSerializer class but
there is a problem. The field students_in_class is already defined as pkfield, whereas I
want to use it as a stringfields in the response of this function
""""
My serializer:
class AddStudentstoClassSerializer(serializers.ModelSerializer):
students_in_class = serializers.PrimaryKeyRelatedField(
many=True, queryset=Student.objects.all()
)
class Meta:
model = Class
fields = ["students_in_class"]
depth = 1
def update(self, instance, validated_data):
slug = self.context["slug"]
stu = validated_data.pop("students_in_class")
/................other codes....../
return instance
Here we can see the student_in_class is defined as pkfield which is ok when using the update api, but when I want to use the get api and call get_all_students_of_a_class I want the field to be stringfield or some other field. How to do that? Also depth= 1 is also not working.
Update:
Treid the following but still not working:
def to_representation(self, instance):
rep = super().to_representation(instance)
# rep["students_in_class"] = instance.students_in_class
rep['students_in_class'] = StudentSerializer(instance.students_in_class).data
return rep
class StudentSerializer(serializers.ModelSerializer):
user = serializers.PrimaryKeyRelatedField(read_only=True)
class Meta:
model = Student
fields = ['user', 'college_name', 'address']
what i got in the response is
{
"students_in_class": {}
}
it is empty dict. what should be done!
You can override you to_representation method like this.
class AddStudentstoClassSerializer(serializers.ModelSerializer):
students_in_class = serializers.PrimaryKeyRelatedField(
many=True, queryset=Student.objects.all()
)
class Meta:
model = Class
fields = ["students_in_class"]
def to_representation(self, instance):
data = {
"students_in_class": # Write your logic here
}
return data
def update(self, instance, validated_data):
slug = self.context["slug"]
stu = validated_data.pop("students_in_class")
/................other codes....../
return instance
I am using django rest framework, and I have an object being created via a modelviewset, and a modelserializer. This view is only accessible by authenticated users, and the object should set its 'uploaded_by' field, to be that user.
I've read the docs, and come to the conclusion that this should work
viewset:
class FooViewset(viewsets.ModelViewSet):
permission_classes = [permissions.IsAdminUser]
queryset = Foo.objects.all()
serializer_class = FooSerializer
def get_serializer_context(self):
return {"request": self.request}
serializer:
class FooSerializer(serializers.ModelSerializer):
uploaded_by = serializers.PrimaryKeyRelatedField(
read_only=True, default=serializers.CurrentUserDefault()
)
class Meta:
model = Foo
fields = "__all__"
However, this results in the following error:
django.db.utils.IntegrityError: NOT NULL constraint failed: bar_foo.uploaded_by_id
Which suggests that "uploaded_by" is not being filled by the serializer.
Based on my understanding of the docs, this should have added the field to the validated data from the serializer, as part of the create method.
Clearly I've misunderstood something!
The problem lies in the read_only attribute on your uploaded_by field:
Read-only fields are included in the API output, but should not be
included in the input during create or update operations. Any
'read_only' fields that are incorrectly included in the serializer
input will be ignored.
Set this to True to ensure that the field is used when serializing a
representation, but is not used when creating or updating an instance
during deserialization.
Source
Basically it's used for showing representation of an object, but is excluded in any update and create-process.
Instead, you can override the create function to store the desired user by manually assigning it.
class FooSerializer(serializers.ModelSerializer):
uploaded_by = serializers.PrimaryKeyRelatedField(read_only=True)
def create(self, validated_data):
foo = Foo.objects.create(
uploaded_by=self.context['request'].user,
**validated_data
)
return foo
DRF tutorial recommend to override perform_create method in this case and then edit serializer so, that it reflect to new field
from rest_framework import generics, serializers
from .models import Post
class PostSerializer(serializers.HyperlinkedModelSerializer):
author = serializers.ReadOnlyField(source='author.username')
class Meta:
model = models.Post
fields = ['title', 'content', 'author']
class ListPost(generics.ListCreateAPIView):
queryset = Post.objects.all()
serializer_class = PostSerializer
def perform_create(self, serializer):
return serializer.save(author=self.request.user)
Cleaner way:
class PostCreateAPIView(CreateAPIView, GenericAPIView):
queryset = Post.objects.all()
serializer_class = PostCreationSerializer
def perform_create(self, serializer):
return serializer.save(author=self.request.user)
class PostCreationSerializer(serializers.ModelSerializer):
author = serializers.PrimaryKeyRelatedField(read_only=True)
class Meta:
model = Post
fields = ("content", "author")
I have tracks and albums. I would like the ability to mark tracks as deleted but not remove them from the database. I would like tracks that are marked as deleted (is_deleted=True) not to show up in the API in my nested serializer.
I have tried a custom "get_queryset" method on TrackSerializer.py but it is not called.
serializers.py
class TrackSerializer(serializers.ModelSerializer):
class Meta:
model = Track
class AlbumSerializer(serializers.ModelSerializer):
tracks = TrackSerializer(many=True)
### How do I limit tracks in the related/nested serializer to tracks on this album that have not been deleted?
models.py
class Track(models.Model):
name = models.CharField()
is_deleted = models.BooleanField(default=False)
album = models.ForeignKey(Album, related_name="tracks")
class Album(models.Model):
name = models.CharField()
I determined that I needed to create a custom ListSerializer because I have used many=True
This is about what I ended up with in serializers.py
class DeletedListSerializer(serializers.ListSerializer):
def to_representation(self, data):
iterable = data.exclude(is_deleted=True) if isinstance(data, models.Manager) else data
return [
self.child.to_representation(item) for item in iterable
]
class TrackSerializer(serializers.ModelSerializer):
class Meta:
model = Track
class AlbumSerializer(serializers.ModelSerializer):
tracks = TrackSerializer(many=True)
### How do I limit tracks in the related/nested serializer to tracks on this album that have not been deleted?
#classmethod
def many_init(cls, *args, **kwargs):
kwargs['child'] = cls()
return DeletedListSerializer(*args, **kwargs)
I don't know how your view looks like. Lets say you are using viewsets. You could overwrite the def destroy() function. In which you get the object and change the state of is_deleted = True
For example:
def destroy(self, request, *args, **kwargs):
instance = self.get_object()
instance.is_deleted = True
instance.save()
return Response(status=status.HTTP_204_NO_CONTENT)
For your second problem i recommend writing an explicit filter for django which uses filters.BaseFilterBackend
For example:
import django_filters
from rest_framework import filters
class TrackFilterBackend(filters.BaseFilterBackend):
def filter_queryset(self, request, queryset, view):
return queryset.filter(is_deleted=False)
Then add this to your view as filter_class = TrackFilterBackend.
You can find more details on DJango REST filtering
You can also use a SerializerMethodField:
class AlbumSerializer(serializers.ModelSerializer):
tracks = SerializerMethodField()
def get_tracks(self, album):
tracks = album.track_set.filter(is_deleted=False)
return TrackSerializer(tracks, many=True).data
I have a method field called followers. I get the list of followers in a SerializerMethodField :
followers = serializers.SerializerMethodField()
I want to format the result with a specific serializer called BaseUserSmallSerializer. How should I implement the method get_followers to achieve that ?
Try this;
followers = BaseUserSmallSerializer(source='get_followers', many=True)
OR
You can use serializer inside methodfield;
def get_followers(self, obj):
followers_queryset = #get queryset of followers
return BaseUserSmallSerializer(followers_queryset, many=True).data
If you prefer a more generic solution:
SerializerMethodNestedSerializer which works same as serializers.SerializerMethodField but wraps the result with the passed serializer and returns a dict
class SerializerMethodNestedSerializer(serializers.SerializerMethodField):
"""Returns nested serializer in serializer method field"""
def __init__(self, kls, kls_kwargs=None, **kwargs):
self.kls = kls
self.kls_kwargs = kls_kwargs or {}
super(SerializerMethodNestedSerializer, self).__init__(**kwargs)
def to_representation(self, value):
repr_value = super(SerializerMethodNestedSerializer, self).to_representation(value)
if repr_value is not None:
return self.kls(repr_value, **self.kls_kwargs).data
Usage
class SomeSerializer(serializers.ModelSerializer):
payment_method = SerializerMethodNestedSerializer(kls=PaymentCardSerializer)
def get_payment_method(self, obj):
return PaymentCard.objects.filter(user=obj.user, active=True).first()
class Meta:
model = Profile
fields = ("payment_method",)
class PaymentCardSerializer(serializers.ModelSerializer):
class Meta:
fields = ('date_created', 'provider', 'external_id',)
model = PaymentCard
The expected output of SerializerMethodNestedSerializer(kls=PaymentCardSerializer)
None or {'date_created': '2020-08-31', 'provider': 4, 'external_id': '123'}
I am new to DRF and I am trying to write custom view / serializer that I can use to update just one field of user object.
I need to make logic just to update the "name" of the user.
I wrote serializer:
class ClientNameSerializer(serializers.ModelSerializer):
class Meta:
model = ClientUser
fields = ('name',)
def update(self, instance, validated_data):
instance.name = validated_data.get('name', instance.name)
instance.save()
return instance
This method is never called. I tried setting breakpoint there and debug it, but it is never called, even if I use PUT, POST or PATCH methods. If I add create method it is being called when I use POST.
This is how my view looks like:
class UpdateName(generics.CreateAPIView):
queryset = ClientUser.objects.all()
serializer_class = ClientNameSerializer
permission_classes = (permissions.IsAuthenticated,)
Does anyone have some suggestion? Thanks!
My models.py looks like this
class ClientUser(models.Model):
owner = models.OneToOneField(User,unique=True,primary_key=True)
phone_number = models.CharField(validators=[PHONE_REGEX],max_length=20,unique=True)
name = models.CharField(max_length=100,blank=True)
status = models.IntegerField(default=1)
member_from = models.DateTimeField('member from',auto_now_add=True)
is_member = models.BooleanField(default=False)
The definition of what methods the endpoint can accept are done in the view, not in the serializer.
The update method you have under your serializer needs to be moved into your view so you'll have something like:
serializers.py
class ClientNameSerializer(serializers.ModelSerializer):
class Meta:
model = ClientUser
views.py
class UpdateName(generics.UpdateAPIView):
queryset = ClientUser.objects.all()
serializer_class = ClientNameSerializer
permission_classes = (permissions.IsAuthenticated,)
def update(self, request, *args, **kwargs):
instance = self.get_object()
instance.name = request.data.get("name")
instance.save()
serializer = self.get_serializer(instance)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
return Response(serializer.data)
Take note that you're overriding the UpdateModelMixin and you might need to change the above code a little bit to get it right.
If you use class UpdateName(generics.CreateAPIView), this will only call a create() method on the serializer.
You should subclass generics.UpdateAPIView instead. And that's it.
You do not have to move your method to the view as suggested in this answer (it is basically copying/duplicating the UpdateModelMixin's update method)
For more information how serializers work regarding saving/updating see the docs here:
One other approach might be the following one:
serializer.py
class ClientNameSerializer(serializers.ModelSerializer):
class Meta:
model = ClientUser
fields = ('name',)
def update(self, instance, validated_data):
instance.name = validated_data.get('name', instance.name)
instance.save()
return instance
views.py
class UpdateName(generics.UpdateAPIView):
queryset = ClientUser.objects.all()
serializer_class = ClientNameSerializer
permission_classes = (permissions.IsAuthenticated,)
def update(self, request, *args, **kwargs):
data_to_change = {'name': request.data.get("name")}
# Partial update of the data
serializer = self.serializer_class(request.user, data=data_to_change, partial=True)
if serializer.is_valid():
self.perform_update(serializer)
return Response(serializer.data)