Home > front end >  how to check if object exist before adding in django api view
how to check if object exist before adding in django api view

Time:09-12

I have a favorite list for course, user can add courses those like to see in future, I want to check course exist in list or not before adding it, if it exists tell it exist before if not add it to list


class AddtoMyCoursesView(viewsets.GenericViewSet):
    serializer_class = MyCoursesListSerializer

    def get_queryset(self, *args, **kwargs):
        pk = self.request.POST.get('pk')
        user = self.request.user
        print(user)
        courses = MyCoursesList.objects.filter(user=user.pk)
        print(courses)
        for course in courses:
            print(course)
            try:
                return MyCoursesList.objects.get_or_create(my_courses=course, id=pk)
            except:
                return Response("Item already exists", status.HTTP_400_BAD_REQUEST)

model


class MyCoursesList(models.Model):
    user = models.ForeignKey('accounts.User', on_delete=models.CASCADE, blank=True)
    courses = models.ForeignKey(Courses, on_delete=models.CASCADE, blank=True,related_name='my_courses')
    added_date = models.DateTimeField(auto_now_add=True)
    teacher = models.ForeignKey(Teacher, on_delete=models.DO_NOTHING, default=1)


class MyCoursesListSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyCoursesList
        fields = ['id', 'user', 'courses', 'added_date', 'teacher']

CodePudding user response:

You can use exists() method in Django

if MyCoursesList.objects.filter(id=pk, user=self.request.user.id).exists():
    return Response("Item already exists", status.HTTP_400_BAD_REQUEST)

CodePudding user response:

Try this

try:
    MyCoursesList.objects.get(id=pk, user_id=user)
except:
    return Response('Item Exists')
  • Related