[Django]-Django add relationships to user model

7👍

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()

1👍

On the currently released Django version(s) [ up to 1.4.x ], the standard practice is to define a profile object. This is preferable to “polluting” the built in user model by extending / modifying it. The upcoming version of Django will allow the creation of custom user models.

In summary:

  • The cleanest solution that can be used with a current production version of Django is to create a profile model and place the “like” and “follow” relationships there
  • The next version of Django will allow you to supply your own User model – that has exactly what you need

1👍

You should try to use the Django Relationships app for this. It is meant for creating relationships between auth.users and you will understand how to create self-referential follows by studying that code. You can then extend it for more generic types or write your own using the Django Content Types Framework

However since Django ORM inherently isn’t exactly defined to be a graph database, you should try to stick to relational database concepts and use a ManyToMany Relationship or ForeignKey as appropriate.

0👍

Add a ManytoMany relationship in your article to the User model. Everytime a user likes one article add him into it. Length of that field will be the number of like in that article.

Leave a comment