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
- [Django]-Passing value along with form in POST data in Django
- [Django]-Custom django-admin commands – AttributeError: 'Command' object has no attribute 'stdout'
- [Django]-Django custom forms select tag
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.
- [Django]-Django serving each app separately in each its port
- [Django]-DRF PrimaryRelatedField when write and NestedSerializer when read?
- [Django]-How to display a name instead of email address with django send_mail?
- [Django]-Django import search path
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.
- [Django]-How to throw custom exception with custom error code on fly in django rest framework and override default fields in exception response
- [Django]-Render to response to a redirected url in Django
- [Django]-Django: How to dynamic filter foreignkey choices by Customizing the Django_Admin
- [Django]-Django – copy header from admin to all templates
- [Django]-MemoryError with django