I'm experiencing a weird problem where one of my serializers is not getting the context and thus failing.
First, the viewset, I've implemented a list method where I'm filtering orders based on some criteria that is dependent on nested relations in the model.
class OrdersInAgendaViewSet(OrderMixin, viewsets.ReadOnlyModelViewSet):
queryset = Order.objects.all()
serializer_class = OrderInAgendaSerializer
permission_classes = (
CanManageOrder,
)
def list(self, request):
final_orders = set()
qs = super(OrdersInAgendaViewSet, self).get_queryset()
# Get only orders that have lines with products that have no rentals objects
for order in qs:
accommodations = False
lines = order.lines.all()
for line in lines:
if line.product.rental:
accommodations = True
break
if not accommodations:
final_orders.add(order.pk)
qs = qs.filter(pk__in=final_orders)
serializer = self.serializer_class(qs, many=True)
return Response(serializer.data)
And now the main Serializer for this ViewSet
class OrderInAgendaSerializer(serializers.ModelSerializer):
lines = LineForAgendaSerializer(many=True, read_only=True)
customer = CustomerInOrderSerializer(many=False, read_only=False)
notes = OrderNoteSerializer(many=True, read_only=True)
class Meta:
model = Order
fields = (
'id',
'date_placed',
'status',
'payment_status',
'email_billing',
'notes',
'customer',
'lines',
)
extra_kwargs = {'date_placed': {'required': False}}
As you can see I'm using 3 more serializers on this one, the one that is failing is LineForAgendaSerializer:
class LineForAgendaSerializer(serializers.ModelSerializer):
product = ProductForAgendaSerializer(many=False, read_only=True)
customers = serializers.SerializerMethodField()
class Meta:
model = Line
fields = (
'starting_date',
'ending_date',
'product',
'customers',
'rents',
)
def get_customers(self, obj):
customers = obj.customerinline_set.all()
session_filter = self.context['request']\
.query_params.get('session', None)
if session_filter is not None:
customers = customers.filter(
sessions__id=session_filter).distinct()
serializer = CustomerInLineForAgendaSerializer(customers, many=True, context=self.context)
return serializer.data
The offending line is in the get_customers method:
session_filter = self.context['request']\
.query_params.get('session', None)
Checking self.context, is empty, so I get KeyError all the time...
How can I pass the context to this serializer...should it be done from the Viewset (if so how?) or from the OrderInAgendaSerializer (and again, how?)
Thanks
Yes you should pass context from your viewset.
On this line :
serializer = self.serializer_class(qs, many=True, context={your context})
Alternatively you can user self.get_serializer() method that should work.
Related
Django time:
I am facing an issue with providing a context to the serializer:
class CommentSerializer(serializers.ModelSerializer):
likes = CustomUserSerializer(many=True,source='likes.all')
class Meta:
fields = 'likes',
model = models.Comment
def get_user_like(self,obj):
for i in obj.likes.all():
if self.context['user'] in i.values():
return self.context['user']
in the view:
class CommentView(viewsets.ModelViewSet):
serializer_class = serializer.CommentSerializer
def get_serializer_context(self): #adding request.user as an extra context
context = super(CommentView,self).get_serializer_context()
context.update({'user':self.request.user})
return context
as you can see, i have overridded get_serializer_context to add user as a context
however, in the serializer side, i am getting KeyError:'user' means the key does not exist, any idea how to set a context?
This is not necessary and inefficient. You can just annotate with:
from django.db.models import Exists, OuterRef
class CommentView(viewsets.ModelViewSet):
serializer_class = serializer.CommentSerializer
def get_queryset(self):
return Comment.objects.annotate(
user_like=Exists(
Like.objects.filter(
comment_id=OuterRef('pk'), user_id=self.request.user.pk
)
)
).prefetch_related('likes')
In the serializer we then add the user_like field:
class CommentSerializer(serializers.ModelSerializer):
likes = CustomUserSerializer(many=True)
user_like = serializers.BooleanField(read_only=True)
class Meta:
fields = ('likes',)
model = models.Comment
I have a model which has specific many to many fields to the user model. Now, to prevent information leaking, I do not want to return the whole related field though the rest framework. But, I want to create some kind of computed field, such that it return True if the requesting user is in the related field, and False otherwise. Is there a way to make this work?
For example, as it stands now, the rest framework will list the users for "user_like" and
"user_bookmark", which I dont want to happen, hence I want to exclude them from the serialized. But I want to have a field, say, named is_liked, which will be true if request.user is in user_like, and false otherwise.
My current setup:
model
class Post(models.Model):
title = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE)
image = models.ImageField(upload_to='dream_photos')
description = models.TextField(max_length=500)
date_added = models.DateTimeField(auto_now_add=True)
user_like = models.ManyToManyField(User, related_name='likes', blank=True)
user_bookmark = models.ManyToManyField(
User, related_name='bookmarks', blank=True)
total_likes = models.PositiveIntegerField(db_index=True, default=0)
tags = TaggableManager()
serialiser
class PostSerializer(TaggitSerializer, serializers.ModelSerializer):
tags = TagListSerializerField()
class Meta:
model = Dream
fields = ('title','user', 'image','description','date_added', 'tags', 'total_likes' )
views
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.prefetch_related('user').all()
serializer_class = PostSerializer
permission_classes = [permissions.IsAuthenticated]
#action(detail=False, methods=['get'], url_path='current-profile', url_name='current-profile')
def current_user_posts(self, request):
# I expected this to add the extra field I required
# But it does not seem to work as expected
queryset = self.get_queryset().filter(user=request.user).annotate(
bookmark=(request.user in "user_bookmark"))
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
Expected behavior when requesting:
{
"id": 1,
"tags": [
"test"
],
"title": "Tets",
"image": "http://127.0.0.1:8000/media/post_photos/photo1648638314.jpeg",
"description": "TEst",
"date_added": "2022-05-20T17:47:55.739431Z",
"total_likes": 0,
"user": 1,
"like": true, // true if current user is in user_like, false otherwise
"bookmark": true // true if current user is in user_bookmark, false otherwise
}
Actual behavior
TypeError: 'in ' requires string as left operand, not SimpleLazyObject
Edit 1:
The answer from here seems to help to resolve the error. Unfortunately, the annotated field does not seem to be returned by the serializer
the edited view:
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.prefetch_related('user').all()
serializer_class = PostSerializer
permission_classes = [permissions.IsAuthenticated]
#action(detail=False, methods=['get'], url_path='current-profile', url_name='current-profile')
def current_user_posts(self, request):
queryset = self.get_queryset().filter(user=request.user).annotate(
bookmark=Exists(Post.user_bookmark.through.objects.filter(
post_id=OuterRef('pk'), user_id=request.user.id))
)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
What you can do is add your custom fields to the serializer with SerializerMethodField and pass the request.user via get_serializer_context in your view. For example:
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.prefetch_related('user').all()
serializer_class = PostSerializer
permission_classes = [permissions.IsAuthenticated]
#action(detail=False, methods=['get'], url_path='current-profile', url_name='current-profile')
def current_user_posts(self, request):
queryset = self.get_queryset().filter(user=request.user)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
def get_serializer_context(self):
context = super(PostViewSet, self).get_serializer_context()
context.update({"request": self.request})
return context
This allows you to sent the request via the context which can be used by the serializer. Now in your serializer you can add this two new fields:
class PostSerializer(TaggitSerializer, serializers.ModelSerializer):
tags = TagListSerializerField()
bookmark = serializers.SerializerMethodField()
like = serializers.SerializerMethodField()
class Meta:
model = Post
fields = ('title','user', 'image','description','date_added', 'tags', 'total_likes', 'bookmark', 'like')
def get_like(self, obj):
return self.context['request'].user in obj.user_like.all()
def get_bookmark(self, obj):
return self.context['request'].user in obj.user_bookmark.all()
When I set a ViewSet with both filtering and list() function -> filtering stops work:
class ClientViewSet(ModelViewSet):
serializer_class = ClientSerializer
queryset = Client.objects.all()
filter_class = ClientFilter
def list(self, request):
serializer = ClientSerializer(self.queryset, many=True)
return JsonResponse(serializer.data, safe=False)
Here is my filter class:
class ClientFilter(FilterSet):
type = CharFilter(name='type', lookup_expr='iexact')
parent_id = NumberFilter(name='parent__id')
title = CharFilter(name='title', lookup_expr='icontains')
class Meta:
model = Client
fields = {
'type', 'parent_id', 'title'
}
Please note
that without a list() method filtering works perfectly, I checked that thousand times. I'm 100 % sure that list() is exactly what causing the issue, I just don't know why and what exactly to do to solve this conflict.
You should use filter_queryset method:
def list(self, request):
queryset = self.filter_queryset(self.queryset)
serializer = ClientSerializer(queryset, many=True)
return JsonResponse(serializer.data, safe=False)
How can I returns serval list in Rest Framework?
I have serializers.py
class HostTypeSerializer(ModelSerializer):
class Meta:
model = HostType
fields = "__all__"
class DiskOSTypeSerializer(ModelSerializer):
class Meta:
model = DiskOSType
fields = "__all__"
class DiskEssenceTypeSerializer(ModelSerializer):
class Meta:
model = DiskEssenceType
fields = "__all__"
I have the three Serializers, and I want to return data like bellow:
{
hosttypes:[the HostTypeSerializer's list data ],
diskostype:[the DiskOSTypeSerializer's list data],
diskessencetype:[the DiskEssenceTypeSerializer's list data],
}
I tried but failed, but I don't know how to do with that:
class DiskPreCreateSerialzer(ModelSerializer):
hosttypes = HostTypeSerializer(many=True, read_only=True)
diskostypes = DiskOSTypeSerializer(many=True, read_only=True)
diskessencetypes = DiskEssenceTypeSerializer(many=True, read_only=True)
class Meta:
fields = (
"hosttypes",
"diskostypes",
"diskessencetypes",
)
In views.py:
class DiskPreCreateAPIView(APIView):
serializer_class = DiskPreCreateSerialzer
permission_classes = []
...
I want to use this Serializer to returns my requirement, but failed, how can I get that?
EDIT
I don't know how to write my DiskPreCreateAPIView now, because I don't know how to get the data to return.
class DiskPreCreateAPIView(APIView):
serializer_class = DiskPreCreateSerialzer
permission_classes = []
def post(self, request):
return Response(data=xxx, status=HTTP_200_OK)
Try to use base Serializer instead of ModelSerializer:
class DiskPreCreateSerialzer(Serializer):
hosttypes = HostTypeSerializer(many=True, read_only=True)
diskostypes = DiskOSTypeSerializer(many=True, read_only=True)
diskessencetypes = DiskEssenceTypeSerializer(many=True, read_only=True)
And in your view pass dict with your lists to this serializer:
class DiskPreCreateAPIView(APIView):
serializer_class = DiskPreCreateSerialzer
permission_classes = []
def post(self, request):
...
serializer = self.serializer_class({
'hosttypes': hosttypes_qs,
'diskostype':diskostype_qs,
'diskessencetype': diskessencetype_qs,
})
return Response(data=serializer.data, status=HTTP_200_OK)
I want to hide specific fields of a model on the list display at persons/ and show all the fields on the detail display persons/jane
I am relatively new to the rest framework and the documentation feels like so hard to grasp.
Here's what I am trying to accomplish.
I have a simple Person model,
# model
class Person(models.Model):
first_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=30, blank=True)
nickname = models.CharField(max_length=20)
slug = models.SlugField()
address = models.TextField(max_length=300, blank=True)
and the serializer class
# serializers
class PersonListSerializer(serializers.ModelSerializer):
class Meta:
model = Person
fields = ('nickname', 'slug')
class PersonSerializer(serializers.ModelSerializer):
class Meta:
model = Person
fields = ('first_name', 'last_name', 'nickname', 'slug', 'address')
and the viewsets.
# view sets (api.py)
class PersonListViewSet(viewsets.ModelViewSet):
queryset = Person.objects.all()
serializer_class = PersonListSerializer
class PersonViewSet(viewsets.ModelViewSet):
queryset = Person.objects.all()
serializer_class = PersonSerializer
at the url persons I want to dispaly list of persons, just with fields nickname and slug and at the url persons/[slug] I want to display all the fields of the model.
my router configurations,
router = routers.DefaultRouter()
router.register(r'persons', api.PersonListViewSet)
router.register(r'persons/{slug}', api.PersonViewSet)
I guess the second configuration is wrong, How can I achieve what I am trying to do?
update:
the output to persons/slug is {"detail":"Not found."} but it works for person/pk
Thank you
For anyone else stumbling across this, I found overriding get_serializer_class on the viewset and defining a serializer per action was the DRY-est option (keeping a single viewset but allowing for dynamic serializer choice):
class MyViewset(viewsets.ModelViewSet):
serializer_class = serializers.ListSerializer
permission_classes = [permissions.IsAdminUser]
renderer_classes = (renderers.AdminRenderer,)
queryset = models.MyModel.objects.all().order_by('-updated')
def __init__(self, *args, **kwargs):
super(MyViewset, self).__init__(*args, **kwargs)
self.serializer_action_classes = {
'list':serializers.AdminListSerializer,
'create':serializers.AdminCreateSerializer,
'retrieve':serializers.AdminRetrieveSerializer,
'update':serializers.AdminUpdateSerializer,
'partial_update':serializers.AdminUpdateSerializer,
'destroy':serializers.AdminRetrieveSerializer,
}
def get_serializer_class(self, *args, **kwargs):
"""Instantiate the list of serializers per action from class attribute (must be defined)."""
kwargs['partial'] = True
try:
return self.serializer_action_classes[self.action]
except (KeyError, AttributeError):
return super(MyViewset, self).get_serializer_class()
Hope this helps someone else.
You can override the 'get_fields' method your serializer class and to add something like that:
def get_fields(self, *args, **kwargs):
fields = super().get_fields(*args, **kwargs)
request = self.context.get('request')
if request is not None and not request.parser_context.get('kwargs'):
fields.pop('your_field', None)
return fields
In this case when you get detail-view there is 'kwargs': {'pk': 404} and when you get list-view there is 'kwargs': {}
I wrote an extension called drf-action-serializer (pypi) that adds a serializer called ModelActionSerializer that allows you to define fields/exclude/extra_kwargs on a per-action basis (while still having the normal fields/exclude/extra_kwargs to fall back on).
The implementation is nice because you don't have to override your ViewSet get_serializer method because you're only using a single serializer. The relevant change is that in the get_fields and get_extra_kwargs methods of the serializer, it inspects the view action and if that action is present in the Meta.action_fields dictionary, then it uses that configuration rather than the Meta.fields property.
In your example, you would do this:
from action_serializer import ModelActionSerializer
class PersonSerializer(ModelActionSerializer):
class Meta:
model = Person
fields = ('first_name', 'last_name', 'nickname', 'slug', 'address')
action_fields = {
'list': {'fields': ('nickname', 'slug')}
}
Your ViewSet would look something like:
class PersonViewSet(viewsets.ModelViewSet):
queryset = Person.objects.all()
serializer_class = PersonSerializer
And your router would look normal, too:
router = routers.DefaultRouter()
router.register(r'persons', api.PersonViewSet)
Implementation
If you're curious how I implemented this:
I added a helper method called get_action_config which gets the current view action and returns that entry in the action_fields dict:
def get_action_config(self):
"""
Return the configuration in the `Meta.action_fields` dictionary for this
view's action.
"""
view = getattr(self, 'context', {}).get('view', None)
action = getattr(view, 'action', None)
action_fields = getattr(self.Meta, 'action_fields', {})
I changed get_field_names of ModelSerializer:
From:
fields = getattr(self.Meta, 'fields', None)
exclude = getattr(self.Meta, 'exclude', None)
To:
action_config = self.get_action_config()
if action_config:
fields = action_config.get('fields', None)
exclude = action_config.get('exclude', None)
else:
fields = getattr(self.Meta, 'fields', None)
exclude = getattr(self.Meta, 'exclude', None)
Finally, I changed the get_extra_kwargs method:
From:
extra_kwargs = copy.deepcopy(getattr(self.Meta, 'extra_kwargs', {}))
To:
action_config = self.get_action_config()
if action_config:
extra_kwargs = copy.deepcopy(action_config.get('extra_kwargs', {}))
else:
extra_kwargs = copy.deepcopy(getattr(self.Meta, 'extra_kwargs', {}))
If you want to change what fields are displayed in the List vs Detail view, the only thing you can do is change the Serializer used. There's no field that I know of that lets you specify which fields of the Serializer gets used.
The field selection on you serializers should be working, but I don't know what might be happening exactly. I have two solutions you can try:
1 Try to change the way you declare you serializer object
#If you aren't using Response:
from rest_framework.response import Response
class PersonListViewSet(viewsets.ModelViewSet):
def get(self, request):
queryset = Person.objects.all()
serializer_class = PersonListSerializer(queryset, many=True) #It may change the things
return Response(serializer_class.data)
class PersonViewSet(viewsets.ModelViewSet):
def get(self, request, pk): #specify the method is cool
queryset = Person.objects.all()
serializer_class = PersonSerializer(queryset, many=True) #Here as well
#return Response(serializer_class.data)
2 The second way around would change your serializers
This is not the most normal way, since the field selector should be working but you can try:
class PersonListSerializer(serializers.ModelSerializer):
nickname = serializers.SerializerMethodField() #Will get the attribute my the var name
slug = serializers.SerializerMethodField()
class Meta:
model = Person
def get_nickname(self, person):
#This kind of method should be like get_<fieldYouWantToGet>()
return person.nickname
def get_slug(self, person):
#This kind of method should be like get_<fieldYouWantToGet>()
return person.slug
I hope it helps. Try to see the APIview class for building your view too.
Somehow close:
If you just want to skip fields in the serilaizer
class UserSerializer(serializers.ModelSerializer):
user_messages = serializers.SerializerMethodField()
def get_user_messages(self, obj):
if self.context.get('request').user != obj:
# do somthing here check any value from the request:
# skip others msg
return
# continue with your code
return SystemMessageController.objects.filter(user=obj, read=False)
I rewrite ModelViewSet list function to modify serializer_class.Meta.fields attribute, code like this:
class ArticleBaseViewSet(BaseViewSet):
def list(self, request, *args, **kwargs):
exclude = ["content"]
self.serializer_class.Meta.fields = [f.name for f in self.serializer_class.Meta.model._meta.fields if f.name not in exclude]
queryset = self.filter_queryset(self.get_queryset()).filter(is_show=True, is_check=True)
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
class BannerArticleViewSet(ArticleBaseViewSet):
queryset = BannerArticle.objects.filter(is_show=True, is_check=True).all()
serializer_class = BannerArticleSerializer
permission_classes = (permissions.AllowAny,)
But it looks not stable, so i will not use it, just share to figure out the best way
My solution.
class BaseSerializerMixin(_ModelSerializer):
class Meta:
exclude: tuple[str, ...] = ()
exclude_in_list: tuple[str, ...] = ()
model: Type[_models.Model]
def get_action(self) -> Optional[str]:
if 'request' not in self.context:
return None
return self.context['request'].parser_context['view'].action
def get_fields(self):
fields = super().get_fields()
if self.get_action() == 'list':
[fields.pop(i) for i in list(fields) if i in self.Meta.exclude_in_list]
return fields
I think it should be like this:
router.register(r'persons/?P<slug>/', api.PersonViewSet)
and you should include a line like this:
lookup_field='slug'
in your serializer class. Like this:
class PersonSerializer(serializers.ModelSerializer):
lookup_field='slug'
class Meta:
model = Person
fields = ('first_name', 'last_name', 'nickname', 'slug', 'address')