我有一个适用于所有用户的 facebook 朋友表,并且希望为 User 提供一个多对多字段,但在保存数据时遇到了问题。
这是我的代码:
我的模型:
class FacebookFriend(models.Model):
user = models.ManyToManyField(User)
name = models.CharField(max_length="100", unique=False, db_index=True)
fid = models.CharField(max_length="30", unique=False, db_index=True)
birthday = models.DateTimeField(default="1776-07-04")
gender = models.CharField(max_length="10", default="NoData")
avatar = models.URLField()
我的管理:
from django.db import models
from django.contrib.auth.models import User
from facepy import GraphAPI
from social_auth.signals import socialauth_registered
def facebook_friend_data(sender, user, response, details, **kwargs):
if sender == FacebookBackend:
dict = UserSocialAuth.objects.filter(user=user.id).get()
access_token = dict.extra_data['access_token']
uid = dict.uid
graph = GraphAPI(access_token)
friends = graph.get(uid + '/friends?fields=id,name,birthday,gender,picture')
from datetime import datetime
from urllib2 import HTTPError
try:
for f in friends['data']:
friend = FacebookFriend()
friend.fid = f['id']
friend.name = f['name']
try:
friend.gender = f['gender']
except KeyError:
pass
try:
bs= f['birthday'].split('/')
if len(f['birthday'])==10:
formatted_bday= bs[2] + '-' + bs[0] + '-' + bs[1]
else:
formatted_bday= '1900-' + bs[0] + '-' + bs[1]
try:
friend.birthday = datetime.strptime(formatted_bday, '%Y-%m-%d')
except ValueError:
pass
except KeyError:
pass
friend.avatar = f['picture']
friend.save()
friend.user.add(user)
except HTTPError:
pass
socialauth_registered.connect(facebook_friend_data, sender=None)
我的错误:
IntegrityError at /complete/facebook/
duplicate key value violates unique constraint "users_facebookfriend_fid_key"
我正在使用 Django Social Auth 进行我的 facebook 处理。我知道问题出在我的模型以及我如何保存数据,但我不知道该怎么做。
谢谢,如果您还需要什么,请告诉我。