DoesNotExist: Following matching query does not exist.

I have a ‘twitter’ like application where the user add information about twitter post followers and who is following the user.

However, I am getting error. DoesNotExist: Following matching query does not exist. please, help.
Error on line: follow = Following.objects.get(user=request.user).
It is true that the table has no record. But, how can I do that first time?


        data = json.loads(request.body)
        actiontodo = data.get("actiontodo", "")
        
        if (actiontodo =='Follow'):
            
            post_creater = User.objects.get(username=post_creater)
            follow = Following.objects.get(user=request.user)**
            follow.following.add(post_creater)
            follow.save()
            follow_count = follow.following.count()

            logged_user = User.objects.get(username=request.user)
            follow = Following.objects.get(user=post_creater)
            follow.follower.add(logged_user)
            follow.save()         


            return JsonResponse({"message": "User is followed."+follow_count}, status=201)

Model

class Following(models.Model):
    user = models.ForeignKey("User",on_delete=models.CASCADE,null=True, blank=True, related_name="User_following")
    following = models.ManyToManyField("User", max_length=None, blank=True, related_name="following")
    follower = models.ManyToManyField("User", max_length=None, blank=True, related_name="follower")

    def serialize(self):
        return {
            
            "user": self.user.username,
          
            }

A problem here is that you have Following with a ForeignKey relationship to User. That can create many different potential problems given you could now have multiple overlapping lists of follower and following for the same user.

What you might want to do is change that field to a OneToOne field to User, and when the User object is created, create the corresponding Following instance. (You can think of this as being an implementation of the “profile” model of User objects.)

However, this still leaves you with the potential relationship integrity issue that you could have the situation in your data where “A” follows “B”, but “B” doesn’t show that it’s being followed by “A”.

To maintain data integrity, what you really want to do is have a completely separate table, with two FK fields and a constraint to prevent someone from following themselves.
e.g.:

class Followers(...):
    follower = ForeignKey(User)
    followed = ForeignKey(User)
    class Meta:
        unique_together = [['follower', 'followed']]

Thank you for the reply.
I changed the model. However, getting another error now,
django.core.exceptions.FieldError: Cannot resolve keyword ‘user’ into field.

class Followers(models.Model):
    follower = models.ForeignKey("User", on_delete=models.CASCADE, max_length=None,null=True, blank=True, related_name="fwg")
    followed = models.ForeignKey("User", on_delete=models.CASCADE, max_length=None,null=True, blank=True, related_name="fwr")
    class Meta:
        unique_together = [['follower', 'followed']]
if (actiontodo =='Follow'):
            
            #Adding the 'post' creater in the current logged in user's 'followed' record
            post_creater = User.objects.get(username=post_creater)
            **followd = Followers.objects.get(user=request.user)**
            followd.followed.add(request.user)
            followd.save()
            followd_count = followd.followed.count()

            #Adding the current logged in user to 'post' creater's 'follower' record
            logged_user = User.objects.get(username=request.user)
            followr = Followers.objects.get(user=post_creater)
            followr.follower.add(logged_user)
            followr.save()         
            return JsonResponse({"message": "User is followed."+followd_count}, status=201)

You don’t have a field named user in your Followers model. (You don’t need one.) You’re not creating a row associated with a user - you’re creating a row showing the direct relationship between the two people.

(Note: You do not want either blank=True or null=True for this model either - it makes no sense to allow that.)

I am not getting it. Now i am getting error 'AttributeError: ‘ForwardManyToOneDescriptor’ object has no attribute ‘add’.

Correct - you’re not using a ManyToMany relationship any more at all.

This new table is just a list of followers and followed.

You are creating a new instance of the Followers model for each combination of a follower and followed.

I created new instances for ‘followed’ and ‘follower’.
For example, for ‘Logged In’ user, ‘creater of the post’ is included in ‘followed’ record.
And for ‘Creater of the post’, ‘Logged In’ user is added in the ‘follower’ record.
It seems it does allow duplicate records because every time it creates new instance instead of adding the record into same column. Because ‘Follower’ and ‘Followed’ column suppose to have multiple entries for each user, for example, for user X, Followed = [‘Y’,‘Z’].

if (actiontodo =='Follow'):
            
            #Adding the 'post' creater in the current logged in user's 'followed' record
            post_creater = User.objects.get(username=post_creater)
            follwed = Followers()
            follwed.followed = post_creater
            follwed.save()
            
            #Adding the current logged in user to 'post' creater's 'follower' record
            logged_user = User.objects.get(username=request.user)
            follwer = Followers()
            follwer.follower = logged_user
            follwer.save()           

            return JsonResponse({"message": "User is followed."}, status=201)

No.
It’s two rows:
Follower: X, Followed Y
Follower: X, Followed Z

Thank you for the reply. How does the new instance know that connection between the ‘Logged In’ user and ‘Post creater’? Because creating a new instance is not referrering to the current logged in user, for example,

            post_creater = User.objects.get(username=post_creater)
            follwed = Followers()
            follwed.followed = post_creater
            follwed.save()

Here, new instance is assignig the post_creater to which User’s ‘followed’ record?
How can one se the total ‘followed’ for one particular user? for example, ‘count’ property needs some kind of filtering based on ‘User’-

You’ve got a model with two values, the follower and the followed.

You’ve got two values, the post_creater and the logged_user.

You want to create one Followers object with followed=post_creater and follower=logged_user.

If you want to find out how many followers a particular user has, it’s
Followers.objects.filter(followed=particular_user).count()

Thank you very much!