问题
In Django model I am making a table 'followers', which has:
user's id. (this is followed by)
user's id (this is follower)
that's simple a user can follow other users.
How should I define the model in Django?
I tried this, but does not work:
user = models.ForeignKey('self')
follower_id = models.ForeignKey('self')
How should this be done?
thanks
回答1:
The 'self' argument won't work unless you have a model called self
.
Assuming that your assignment model is called Following
, and you're using the built in User
model then you can do:
class Following(models.Model):
target = models.ForeignKey('User', related_name='followers')
follower = models.ForeignKey('User', related_name='targets')
This will likely need some further uniqueness and validation logic.
Note the related_name
attribute, see https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.ForeignKey.related_name. This means that for a given user object you can do user.targets.all()
to get users they follow, and user.followers.all()
to get users who follow them.
Note also that Django returns target model instances, not IDs, in the ORM. This means that even though the underlying table may be called follower_id
, in the python code following.follower
will return an actual User object.
回答2:
Seeing as Following
is actually the through table for the many-to-many relationship between Users. I would create a Profile
model which extends the Django User
model, and then declare the many-to-many relationship (using ManyToManyField
).
from django.contrib.auth.models import User
from django.db import models
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
following = models.ManyToManyField(User, related_name='followers')
来源:https://stackoverflow.com/questions/40069192/django-models-database-design-for-user-and-follower