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?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With