Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django add relationships to user model

I have a django project using the built in user model.

I need to add relationships to the user. For now a "like" relationship for articles the user likes and a "following" relationship for other users followed.

What's the best way to define these relationships? The django doc recommends creating a Profile model with a one on one relation to the user to add fields to the user. but given no extra fields will be added to the user profile in my case this is overkill.

Any suggestions?

like image 936
applechief Avatar asked Sep 14 '25 20:09

applechief


1 Answers

For these special many-to-many relationships, you have to define them in models:

class UserFollowing(models.Model):
    user = models.ForeignKey(User, related_name='following')
    following = models.ForeignKey(User, related_name='followed_by')

So then if you have a user, you can do things like:

user = User.objects.get(...)
user.following.all() # all users this user is following
user.followed_by.all() # all users who follow this user

As for articles, you have setup a similar schema:

class ArticleLike(models.Model):
    article = models.ForeignKey(Article, related_name='likes')
    like = models.ForeignKey(User, related_name='articles_like')

Article.objects.get(...).likes.all()

User.objects.get(...).articles_like.all()
like image 84
miki725 Avatar answered Sep 16 '25 10:09

miki725