让Django的“用户”系统成为“朋友”的最好方法

时间:2010-12-30 17:26:48

标签: django

我正在使用Django的授权系统在我的应用程序上创建帐户。

使用授权系统制作“朋友”系统的最佳方法是什么?我希望能够将用户链接在一起,但他们必须先接受好友请求,我还要保留他们成为好友的日期。

3 个答案:

答案 0 :(得分:21)

M2M字段几乎可以让你到达那里,但只存储关系,而不是它创建的日期。如果你能在没有友谊约会的情况下进行管理,那将会简单得多。

否则你会想要创建这样的模型:

class Friendship(models.Model):
    created = models.DateTimeField(auto_now_add=True, editable=False)
    creator = models.ForeignKey(User, related_name="friendship_creator_set")
    friend = models.ForeignKey(User, related_name="friend_set")

你可能想要在user profile model上创建一个方法来理解这种关系。理想情况下,它应该得到这样的东西:

>> User.userprofile.friends()
[{'name': "Joe", 'created': 2010-12-01},]

答案 1 :(得分:6)

我做过这些:

models.py

class FriendMgmt(models.Model):
    """
        friends table
    """
    user = models.ForeignKey(User)
    friend = models.ForeignKey(User, related_name="friends")

forms.py

class FriendMgmtForm(forms.Form):
    """
        Manages friends connections
    """
    friend = forms.CharField(max_length=100,required=False)

views.py

def my_friends(request):
    """
        used for Displaying and managing friends
    """
if request.method == 'POST':

    form = FriendMgmtForm(request.POST)
    if form.is_valid():

        user = User.objects.get(id=80)
        friend_manage = FriendMgmt(user=request.user, friend= user)
        friend_manage.save()

        return HttpResponseRedirect('/myfriends/')

else:
    form = PdfValidationForm()

user = request.user
profile = UserProfile.objects.get(user=user)
full_name = user.get_full_name()
email = user.email
area_interest = profile.area_of_interest
designation = profile.designation
friends = FriendMgmt.objects.filter(user=request.user)


return render_to_response('friends.html',{'form': form,
                                      'full_name':full_name,
                                      'email':email,
                                      'area_interest':area_interest,
                                      'designation':designation,
                                      'friends':friends,

                                      }
                          )

url.py

 url(r'^myfriends/$',my_friends)

答案 2 :(得分:1)

class UserProfile(models.Model):

    user = models.ForeignKey(User, unique=True)
    #other fields

    def get_friends(self):
        user = self.user
        return Friendship.objects.filter(Q(creator=user)|Q(friend=user))


    #then you can call elsewhere

    friends = user.get_profile().get_friends().all()