我知道我在这里重新发明轮子,但我不喜欢django-friendship
而想自己写。
因此,我有自定义用户模型Person
class Person(AbstractBaseUser, PermissionsMixin):
username = models.CharField(('username'), max_length=75, unique=True,
help_text=('Required. 30 characters or fewer. Letters, numbers and '
'@/./+/-/_ characters'),
validators=[
validators.RegexValidator(re.compile('^[\w.@+-]+$'),
('Enter a valid username.'), 'invalid')
])
....more other fields....
friend = models.ForeignKey('self', related_name="friends", default=None, null=True)
正如你所看到的,我有自己的外键或其他单词oneToMany的关系。
以下是我在views.py中添加好友的内容
def add_friend(request, username):
if request.user.is_authenticated():
user = Person.objects.get_by_natural_key(username)
if user is not None:
user.friend = request.user /// here
return HttpResponseRedirect('/profile/')
我正在通过用户名获取要添加到朋友的用户,并将用户字段(朋友)设置为当前用户(请求用户)。但是,我认为我在这里做错了。
我试图谷歌它,但没有找到ForeignKey('self')
答案 0 :(得分:3)
最后我做了另一种方式
我使用ManyToMany和类关系
而不是ForeignKeyclass Person(AbstractBaseUser, PermissionsMixin):
... things here...
relationships = models.ManyToManyField('self', through='Relationship',
symmetrical=False,
related_name='related_to')
和班级
class Relationship(models.Model):
from_person = models.ForeignKey(Person, related_name='from_people')
to_person = models.ForeignKey(Person, related_name='to_people')
要在我的视图中添加用户,我有
def add_friend(request, username):
if request.user.is_authenticated():
user = Person.objects.get_by_natural_key(username)
Relationship.objects.get_or_create(
from_person=request.user,
to_person=user)
return HttpResponseRedirect('/profile/')
并显示用户列表
def show_friends(request, username):
user = Person.objects.get_by_natural_key(username)
rel = user.relationships.filter(
to_people__from_person=user)
args = {'friends': rel}
return render(request, "profile/friend_list.html", args)
您可以看到更多here。这篇文章帮助我理解了我做错了什么以及应该改变什么。