0
我有一個Facebook好友表的所有用戶,並希望有用戶多對多場,但在保存數據遇到的問題。Django的多對多場在Facebook上的朋友ID用戶保存錯誤
這裏是我的代碼:
我的模型:
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的社會身份驗證爲我的Facebook處理。我知道這個問題出現在我的模型中,以及我如何保存數據,我不知道該怎麼做。
感謝,讓我知道你需要什麼。
你發現了這個解決辦法嗎?我目前面臨同樣的問題 – 2014-04-02 15:07:48