I need to create a DRF list view that shows each course along with a boolean field signifying whether the user requesting the view is subscribed to the course.
Course subscriptions are stored in the following model:
class Subscription(models.Model):
user = models.ForeignKey(
CustomUser, related_name='subscriptions', null=False,
on_delete=CASCADE)
course = models.ForeignKey(
Course, related_name='subscriptions', null=False,
on_delete=CASCADE)
class Meta:
ordering = ['course', 'user']
unique_together = [['user', 'course']]
This is the view I am writing:
class CourseListView(generics.ListAPIView):
permission_classes = [IsAuthenticated, ]
queryset = Course.objects.all()
serializer_class = CourseSerializer
def isSubscribed(self, request, course):
sub = Subscription.objects.filter(
user=request.user, course=course).first()
return True if sub else False
def list(self, request, format=None):
queryset = Course.objects.all()
serializer = CourseSerializer(queryset, many=True)
return Response(serializer.data)
I am looking for a way to modify the list method, so as to add to the response the information about whether request.user is subscribed to each of the courses.
The best solution I have for now is to construct serializer manually, which would look (at the level of pseudo-code) something like this:
serializer = []
for course in querySet:
course['sub'] = self.isSubscribed(request, course)
serializer.append(CourseSerializer(course))
I suspect there should be a better (standard, idiomatic, less convoluted) way for adding a custom field in a list view, but could not find it. In addition, I am wondering whether it is possible to avoid a database hit for every course.
You can do that easily with Exists:
just change your queryset in your view:
from django.db.models import Exists, OuterRef
class CourseListView(generics.ListAPIView):
permission_classes = [IsAuthenticated, ]
serializer_class = CourseSerializer
def get_queryset(self):
subquery = Subscription.objects.filter(user=request.user, course=OuterRef('id'))
return Course.objects.annotate(sub=Exists(subquery))
and add a field for it in your serializer:
class CourseSerializer(serializers.ModelSerializer):
sub = serializers.BooleanField(read_only=True)
class Meta:
model = Course
fields = '__all__'
Related
view.py
class charity_totals(generics.ListAPIView):
serializer_class= CharityTotalSerializer
queryset=Transaction.objects.all()
def get_queryset(self):
queryset = super().get_queryset()
user_id = self.request.GET.get('userID')
if user_id is None:
return queryset
queryset = queryset.filter(userID=user_id)
return queryset.values('charityID').annotate(total_donation=Sum('transactionAmount'))
serializer.py
class CharityTotalSerializer(ModelSerializer):
charity_name= serializer.ReadOnlyField(source='charityID.charityName')
total_donation= serializer.DecimalField(max_digits=64,decimal_places=2)
class Meta:
model = Transaction
fields = ['charity_name','total_donation']
model
class Transaction(models.Model):
transactionAmount = models.DecimalField(max_digits=6, decimal_places=2)
userID = models.ForeignKey(User,on_delete=models.CASCADE)
charityID = models.ForeignKey(Charity,on_delete=models.CASCADE, related_name='charity_set')
processed = models.BooleanField(auto_created=True, default=False)
transactionDate = models.DateField(auto_now_add=True)
Off of a request such as this http://localhost:8000/requests/charitytotal/?userID=1 my json response is limited to just the [{"total_donation":"3.00"},{"total_donation":"17.00"}] and is not including the charity names that are specified in the serializer. From what I understand the .values should return a dict of both the charityID and the total_donation that was specified which should be able to interact with my serializer. Any Insight would be appreciated
That is because you are returning Values queryset from get_queryset method when you are getting the value of userID in request.GET. Also I assume it is important for you return that way so that you can group by and sum values of total donation. So, I think you can approach something like this:
First, change get_queryset method to return the name of the charity annotated:
from django.db.models import F, Sum
...
def get_queryset(self):
queryset = super().get_queryset()
user_id = self.request.GET.get('userID')
if user_id is not None:
queryset = queryset.filter(userID=user_id)
return queryset.values('charityID').annotate(total_donation=Sum('transactionAmount')).annotate(charity_name=F('charityID__charityName'))
Then update the serializer like this:
class CharityTotalSerializer(ModelSerializer):
charity_name= serializer.ReadOnlyField() # no need to define source
total_donation= serializer.DecimalField(max_digits=64,decimal_places=2)
class Meta:
model = Transaction
fields = ['charity_name','total_donation']
Also, better to have charityName unique(using unique=True in models), so that it does not produce confusing results.
You have to put it into Serializer and it will work fine.
charity_name = serializer.SerializerMethodField()
def get_charity_name(self, instance):
return instance.charityID.name
I am trying to get only courses belonging to a particular user below I have the model, serializer and view I am using to try and achieve this. If I delete the entire get_queryset function from the view the api returns the appropriate user and every course created by every user. If get_queryset remains, the api always returns user not found and still gives every course that exists. Can anyone point me to how I can achieve my desired result.
view:
class UserDetail(generics.RetrieveUpdateDestroyAPIView):
permission_classes = [IsProfileOwnerOrReadOnly]
# queryset = User.objects.all()
serializer_class = UserSerializer
def get_queryset(self):
user = self.request.user
queryset = User.objects.all()
if user is not None:
queryset = queryset.filter(courses__owner_id=user.id)
return queryset
serializer
class UserSerializer(serializers.ModelSerializer):
courses = serializers.PrimaryKeyRelatedField(
many=True, queryset=Course.objects.all())
class Meta:
model = User
fields = ['id', 'username', 'courses']
Model
class Course (models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
pub_date = models.DateField(default=date.today)
owner = models.ForeignKey('auth.User', related_name='courses', on_delete=models.CASCADE)
def __str__(self):
return self.title
You need to filter objects by user
class CreatePostsView(viewsets.ModelViewSet):
model = Post
serializer_class = PostsSerializer
def get_queryset(self):
user = self.request.user
return Post.objects.filter(owner=user)
class CoursesByOwnerView(RetrieveModelMixin, GenericViewSet):
serializer_class = YourModelSerializer
authentication_classes =[TokenAuthentication,]
permission_classes = [IsAuthenticated,]
def list(self, request, *args, **kwargs):
course_taker = self.request.user
courses = YourModel.objects.filter(owner=course_taker).values('your_model_fields')
return Response(courses)
Given your answer in the comments:
Either you use self.request.user given by the authentication middleware. In this case, it will only work for authenticated users, and you can't see courses for another User.
Either you use the endpoint users/<int:pk>/ you mentioned. In this case, you can fetch the user with:
class UserDetail(generics.RetrieveUpdateDestroyAPIView):
permission_classes = [IsProfileOwnerOrReadOnly]
serializer_class = UserSerializer
def get_queryset(self):
return UserDetail.objects.filter(pk=self.kwargs["pk"])
See this thread if you need another example: Django 2.0 url parameters in get_queryset
EDIT: In both cases, change your UserSerializer with:
class UserSerializer(serializers.ModelSerializer):
courses = serializers.PrimaryKeyRelatedField(
many=True, read_only=True)
class Meta:
model = User
fields = ['id', 'username', 'courses']
I've been spending hours on queryset handling of ManyToMany field type.
I want to GET objects(model B) which has ManyToMany relationship with another object(model A), by using filter on model A.
views.py
I get my_user_id from urls.py, which is str.
id part works fine, but...
class UserUserId(generics.RetrieveUpdateAPIView):
#permission_classes = (IsOwner,)
queryset = User.objects.all()
serializer_class = UserSerializer #serializer for User model
def get(self, *args, **kwargs):
id = self.kwargs['my_user_id']
return self.queryset.filter(user_id=id).user_schedules.all()
urls.py
path('user/<str:my_user_id>', views.UserUserId.as_view()),
models.py
class User(models.Model):
user_id = models.TextField(blank=True, null=True)
user_schedules = models.ManyToManyField('Schedule',
related_name='%(class)s_id')
class Schedule(models.Model):
sched_id = models.IntegerField(blank=True, null=True)
sched_name = models.TextField(blank=True, null=True)
It gives me following error :
AttributeError: 'QuerySet' object has no attribute 'user_schedules'
I tried to resolve this issue by put [0] at the end of filter(), but It seems wrong and It doesn't work if I have to check multiple User objects.
So how can I GET user_schedules list of specific User whose user_id is my_user_id?
I'm stuck on this for hours, any help would be much appreciated.
You want to get data for an instance, but your code is trying to get it from a queryset.
The following lines should help you out:
class UserUserId(generics.RetrieveUpdateAPIView):
#permission_classes = (IsOwner,)
queryset = User.objects.all()
serializer_class = UserSerializer #serializer for User model
def get(self, *args, **kwargs):
id = self.kwargs['my_user_id']
user = User.objects.get(id=id)
return list(user.user_schedules.all())
First of all, I think you probably want to use a different serializer (something like SchedulerSerializer) since you suggest that you want to serialize, well, Schedules.
You can obtain all Schedules for a User with a given user_id with:
class UserUserId(generics.RetrieveUpdateAPIView):
#permission_classes = (IsOwner,)
queryset = Schedule.objects.all()
serializer_class = UserSerializer #serializer for User model
def get(self, *args, **kwargs):
id = self.kwargs['my_user_id']
return self.queryset.filter(user__user_id=id)
We thus query over the Schedule model, and filter such that we retrieve all Schedules for which there exists a related User with user_id=id.
I've been using select_related() to speed up a large DRF call with great success, but I've hit a wall.
My main serializer references two other serializers, and one of those references yet another serializer. I'm unsure as how to implement prefetching in the second level serializer.
serializer.py
class DocumentsThinSerializer(serializers.ModelSerializer):
class Meta:
model = Documents
fields = ('confirmed', )
class PersonThinSerializer(serializers.ModelSerializer):
documents = DocumentsThinSerializer()
class Meta:
model = Person
fields = ('name', 'age', 'gender')
class EventThinSerializer(serializers.ModelSerializer):
day = DayThinSerializer()
person = PersonThinSerializer()
#staticmethod
def setup_eager_loading(queryset):
return queryset.select_related('day', 'person')
class Meta:
model = Event
views.py
class EventList(generics.ListAPIView):
authentication_classes = (SessionAuthentication, BasicAuthentication)
permission_classes = (IsAuthenticated,)
queryset = Event.objects.all()
serializer_class = EventThinSerializer
def get_queryset(self):
return self.get_serializer_class().setup_eager_loading(queryset)
As you can see, I'm using the static method setup_eager_loading() to get things going, but I can't find a queryset hook for my PersonThinSerializer() to get the speedup when accessing the DocumentsThinSerializer() in the same way.
Assuming Documents has a foreign key to Person, you should be able to add "person__documents" to your queryset.select_related in EventThinSerializer.setup_eager_loading:
class EventThinSerializer(serializers.ModelSerializer):
day = DayThinSerializer()
person = PersonThinSerializer()
#staticmethod
def setup_eager_loading(queryset):
return queryset.select_related('day', 'person', 'person__documents')
I have a ModelViewSet where I want to annotate the list() response. I've extended the queryset with an annotation and added the field to the serializer, but the serializer just ignores the new data and doesn't add the field at all in the final data.
I am using a customized get_queryset() too (show abbreviated here) which is definitely getting called and producing the right annotations. It just doesn't show up in the REST API response.
If I set default=None on the serializer field definition, it appears in the response.
class SequenceSerializer(serializers.ModelSerializer):
unread=serializers.IntegerField(read_only=True)
.....
class SequenceViewSet(viewsets.ModelViewSet,ScopedProtectedResourceView):
authentication_classes = [OAuth2Authentication]
queryset = Sequence.objects.all()
serializer_class = SequenceSerializer
.....
def get_queryset(self):
queryset = Sequence.objects.all().filter(<..... some filter>)
queryset = queryset.annotate(unread=FilteredRelation('unreadseq',
condition=Q(unreadseq__userid=self.request.user)))
print("Seq with unread",queryset.values('id','unread')) ## <<<<this shows the correct data
return queryset
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data) ##<<< this is missing the annotation
I have been banging my head against this all day and I can't for the life of me see what's going wrong.
Any ideas please?
--
more info:
class UnreadSeq(models.Model):
userid = models.ForeignKey('auth.User', on_delete=models.CASCADE)
seqid = models.ForeignKey(Sequence, on_delete=models.CASCADE)
class Meta:
unique_together=('seqid','userid')
verbose_name = "UnreadSeq"
verbose_name_plural = "UnreadSeqs"
class Sequence(models.Model):
userid = models.ForeignKey('auth.User', on_delete=models.SET_NULL,null=True)
topic = models.ForeignKey('Topic',on_delete=models.CASCADE,null=False,blank=False)
.....
class Meta:
verbose_name = "Sequence"
verbose_name_plural = "Sequences"
I think that this annotation don't return Integer. Try to annotate (you want to COUNT unreadseq) like this:
def get_queryset(self):
mytopics=getMyTopics(self.request,False)
queryset = Sequence.objects.all().filter(<..... some filter>)
count_unreadseq = Count('unreadseq', filter=Q(unreadseq__userid=self.request.user))
queryset=queryset.annotate(unread=count_unreadseq)
...
EDITED after comments to get unreadseq ids
def get_queryset(self):
mytopics=getMyTopics(self.request,False)
queryset = Sequence.objects.all().filter(<..... some filter>)
unreadseq_ids = UnreadSeq.objects.filter(seqid=OuterRef('pk'), userid=self.request.user).values('pk')
queryset=queryset.annotate(unread=Subquery(unreadseq_ids))
...
Also you need to edit serializer:
class SequenceSerializer(serializers.ModelSerializer):
unread=serializers.IntegerField(read_only=True)
.....