我是Django的新手,为了学习目的,我正在尝试使用linkedn API构建我自己的网站来显示我的个人资料。以下是我的代码示例。看到整个地段:
https://github.com/javiee/django-site
models.py
class Profile(models.Model):
user = models.ForeignKey(User)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
def __str__(self):
return self.first_name, self.last_name
class Education(models.Model):
user = models.ForeignKey(User)
school_name = models.CharField(max_length=100)
field_study = models.CharField(max_length=100)
degree = models.CharField(max_length=100)
start_date = models.CharField(max_length=20)
end_date = models.CharField(max_length=20)
和views.py
profile = Profile(first_name = content['firstName'],
last_name = content['lastName'],
user = request.user)
profile.save()
#Education model
content_educ = content['educations']['values']
for value in content_educ:
education = Education(school_name = value['schoolName'],
user = request.user,
field_study = value['fieldOfStudy'],
degree = value['degree'],
start_date = value['startDate']['year'] ,
end_date = value['endDate']['year'])
education.save()
这一切都有效但我的问题是每次检查链接时,代码会再次保存所有对象。理想情况下,在调用.save()方法时,根据配置文件“更新”字段。我已阅读下一个链接https://docs.djangoproject.com/en/1.7/ref/models/instances/#saving-objects
但是我没有设法使它工作,也许foreigns键没有正确设置所以任何建议/帮助/提示将非常感激。谢谢!
答案 0 :(得分:1)
使用update_or_create()
方法:
Education.objects.update_or_create(
school_name=value['schoolName'],
user = request.user,
defaults={'field_study': value['fieldOfStudy'],
'degree': value['degree'],
'start_date': value['startDate']['year'] ,
'end_date': value['endDate']['year']})
答案 1 :(得分:1)
您遇到的问题是您要在以下行中实例化新的Education实例:
education = Education(school_name = value['schoolName'],
user = request.user,
field_study = value['fieldOfStudy'],
degree = value['degree'],
start_date = value['startDate']['year'] ,
end_date = value['endDate']['year'])
当Django试图保存这些新实例(尚未定义id
的实例)时,Django继续并插入记录而不是进行所需的更新。
要进行更新,您可以尝试获取记录,捕获DoesNotExist
例外:
try:
education = Education.objects.get(school_name=value['schoolName'],
user=request.user,
field_study=value['fieldOfStudy'],
degree=value['degree'],
start_date=value['startDate']['year'],
end_date=value['endDate']['year'])
except Education.DoesNotExist:
education = Education(school_name=value['schoolName'],
user=request.user,
field_study=value['fieldOfStudy'],
degree=value['degree'],
start_date=value['startDate']['year'],
end_date=value['endDate']['year'])
然后应用您想要/需要的任何更新。
或者您可以使用get_or_create
执行相同操作:
(education, created) = Education.objects.get_or_create(school_name=value['schoolName'],
user=request.user,
field_study=value['fieldOfStudy'],
degree=value['degree'],
start_date=value['startDate']['year'],
end_date=value['endDate']['year'])
如果您不想按所有这些值查找实例(它们是AND编辑),但想要使用特定值初始化新实例,则应该查找defaults
关键字get_or_create
。
或者您可以按照catavaran的建议使用update_or_create
。
编辑:或者,如果您只想直接更新记录而不获取它(这也适用于多个对象),您可以使用queryset.update
Education.objects.filter(attribute=value, ...).update(attribute2=value2, ...)