我有以下型号:
class MyUser(User):
# some fields...
contact = models.ManyToManyField("self", through='Contact', symmetrical=False, related_name="contact_set" )
class Contact(models.Model):
user1 = models.ForeignKey( MyUser, related_name="contact_set1")
user2 = models.ForeignKey( MyUser, related_name="contact_set2")
confirmed = models.BooleanField()
和此视图创建联系人
def add_contact( request, username=None ):
if username:
try:
user = MyUser.objects.get(username=username)
except User.DoesNotExist:
user = None
if user:
contact = Contact( user1 = MyUser.objects.get(pk=request.user.id), user2=user, confirmed=False )
contact.save()
return render_to_response( "accounts/add_contact.html", {'user': user,} )
else:
return HttpResponseRedirect("/home")
def list_contacts( request, username=None ):
if username:
try:
user = MyUser.objects.get(username=username)
except User.DoesNotExist:
user = None
else:
user = MyUser.objects.get(pk=request.user.id)
if user:
contacts = user.contacts.all()
return render_to_response("accounts/list_contacts.html", {'contacts': contacts,} )
else:
return HttpResponseRedirect("/home")
现在好了......代码应该足够详细,所以我将简要解释一下:社交网络,用户将其他人添加到他们的联系人(“朋友”,“好友”,无论你怎么称呼它)。如果用户A添加用户B,则B也与A ...
联系代码有效......但只有单向。如果我以用户A身份登录并想要将用户B添加到我的联系人中,则B将显示在我的联系人列表中,但不是相反。但是我也希望出现在B的联系人列表中 - 它应该没有区别,谁添加了谁。我该如何管理?