Issue
My application already has some existing users. Now, I want to add a 'Follower' feature, so I created a Follower model:
class User(AbstractUser):
pass
class Follower(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='follower', null=True)
following = models.ManyToManyField(User, related_name='following', blank=True)
Is there a way I can set the existing Users as its default for the user(follower) column in Follower model?.
Upon clicking the follow button, in the backend, I coded it so that if the user (follower) in the Follower model does not exist, it will create the user (follower) and then add the followed user to its 'following'. Otherwise, it will immediately add the followed user to its 'following' in the Follower model. IT WORKS. BUT. I want to know if there is still any other way to do it in the models.py
.
Solution
Is there a way I can set the existing Users as its default for the user(follower) column in
Follower
model?.
No, or at least not without all sorts of dirty fixes like inspecting the call stack. In fact it is not even said that there is a current user, since some codeflows could run and trigger logic, without a user attached to it. For example a management command, or some view that does not require a user to be logged in.
But it would also violate the model-view-controller (MVC) architecture [wiki] of Django where the model layer should be unaware of what the views are doing with the logic.
The modeling also is a bit odd: a Follower
is a user
and a set of User
s that are following
? Then that means there are two junction tables involved.
You likely just want to work with a non-symmetrical ManyToManyField
:
class User(AbstractUser):
followers = models.ManyToManyField(
'self', related_name='followers', symmetrical=False
)
Answered By - willeM_ Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.