Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 @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?

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading