Home > Blockchain >  How to delete a single data from database in django (not deleting the entire row)
How to delete a single data from database in django (not deleting the entire row)

Time:11-30

To give you an understanding of my problem, I am showing my code first, then my question.

In models.py:

class Post(models.Model):
    content = models.CharField(max_length=140)
    date_created = models.DateTimeField(auto_now_add=True)
    poster = models.ForeignKey(User, on_delete=models.CASCADE)
    likes = models.IntegerField(default=0)
    liked_by = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name='liked_by', blank=True, null=True)

  
    def serialize(self):
        return {
            "id": self.id,
            "poster": self.poster.username,
            "poster_image_url": self.poster.image_url,
            "date_created": self.date_created.strftime("%b %d %Y, %I:%M %p"),
            "content": self.content,
            "likes": self.likes,}

In views.py:

 @csrf_exempt
    def get_post(request, post_id):
        post = Post.objects.get(pk=post_id)
        if request.method == "GET":
            return JsonResponse(post.serialize())
        elif request.method == "PUT":
            data = json.loads(request.body)
            if data.get('likes') is not None:
                if data['likes'] > post.likes:
                    post.likes = data['likes']
                    post.liked_by = request.user
                else:
                    post.likes = data['likes']
                    post.liked_by.remove(request.user)
        post.save()
        return HttpResponse(status=204)

I need to remove request.user from liked_by column in the post object. But this error occurs:

AttributeError: 'User' object has no attribute 'remove'

How can I solve the problem?

CodePudding user response:

You can set the field value to None, which in effect removes the association between the post model instance and the user model.

You don't need request.user, since the relationship is many-to-one (post model instance can be related to only one user).

post.liked_by = None
post.save()
  • Related