26👍
First, you should understand how to store additional information about users. It requires another model that has a relation to one user, the “profile” model.
Then, you could use an M2M field, assuming you’d use django-annoying, you could define your user profile model as such:
from django.db import models
from annoying.fields import AutoOneToOneField
class UserProfile(models.Model):
user = AutoOneToOneField('auth.user')
follows = models.ManyToManyField('UserProfile', related_name='followed_by')
def __unicode__(self):
return self.user.username
And use it as such:
In [1]: tim, c = User.objects.get_or_create(username='tim')
In [2]: chris, c = User.objects.get_or_create(username='chris')
In [3]: tim.userprofile.follows.add(chris.userprofile) # chris follows tim
In [4]: tim.userprofile.follows.all() # list of userprofiles of users that tim follows
Out[4]: [<UserProfile: chris>]
In [5]: chris.userprofile.followed_by.all() # list of userprofiles of users that follow chris
Out[5]: [<UserProfile: tim>]
Also, note that you could check / reuse apps like django-subscription, django-actstream, django-social (harder to use probably)…
You might want to take a look at the django packages for notifications and activities as they all require some follow/subscription database design.
4👍
This is how I would do it:
class Tweeter(models.Model):
user = models.ManyToManyField('self', symmetrical=False, through='Relationship')
class Relationship(models.Model):
who = models.ForeignKey(Tweeter, related_name="who")
whom = models.ForeignKey(Tweeter, related_name="whom")
In the shell,
In [1]: t = Tweeter()
In [2]: t.save()
In [3]: f = Tweeter()
In [4]: f.save()
In [5]: r=Relationship()
In [6]: r.who=t
In [7]: r.whom=f
In [8]: r.save()
In [18]: Relationship.objects.all()[0].who.id
Out[18]: 1LIn [19]: Relationship.objects.all()[0].whom.id
Out[19]: 2L
- RuntimeError: __class__ not set defining 'AbstractBaseUser' as <class 'django.contrib.auth.base_user.Abstract BaseUser'>. Was __classcell__ propagated
- Django test: TransactionManagementError: You can't execute queries until the end of the 'atomic' block
- Django. Error message for login form
- Subclassing Django ModelForms
1👍
Edit: Makes more sense to use ManyToManyField, as the commenter suggests. Users can have 0-x User followers, and Users can follow 0-x Users.
https://docs.djangoproject.com/en/1.3/ref/models/fields/#manytomanyfield
Without going into code, not much more to be said.
- Django – forms.FileField() initial value
- Running collectstatic on server : AttributeError: 'PosixPath' object has no attribute 'startswith'
- Django 1.7 where to put the code to add Groups programmatically?
- Django order_by a property
- Python Social auth authentication via access-token fails