假设我有以下函数,它以用户定义对象的形式从服务器检索数据。例如,让我们将对象定义为 PersonalEntry。
def retrieve_people()
// returns a list of all latest people objects, with fields equal to those in PersonEntry
def retrieve_books()
// returns a list of all latest book objects regardless of author, with fields equal to those in BookEntry, contains attribute,
两个用户定义的类都有一个 .as_dict() 方法,该方法在字典中返回其所有属性。
我想在调用此函数时更新模型(即,如果该模型的实例已经存在,则更新字段,否则,定义模型的新实例)。这是我目前的设置。
class PersonEntry(models.Model):
name = models.CharField(max_length = 50)
age = models.IntegerField()
biography = models.CharField(max_length = 200)
def update_persons():
try:
temp = retrieve_person()
for person in temp:
match = PersonEntry.objects.filter(name = person.name(), age = person.age())
match.update(**person.as_dict())
except DoesNotExist:
PersonEntry.create(**person.as_dict())
class BookEntry(models.Model):
author = models.ForeignKey(PersonEntry)
author_name = models.CharField(max_length = 50) //books return redundant info
author_age = models.IntegerField() //books return redundant info
title = models.CharField(max_length = 50)
summary = models.CharField(max_length = 200)
def update_books():
try:
temp = retrieve_books()
for book in temp:
match = BookEntry.objects.filter(title = temp.title())
match.update(**book.as_dict(), associate_person(book.author_age(), book.author_name()))
except DoesNotExist:
BookEntry.create(**book.as_dict(), associate_person(book.author_age(), book.author_name())
def associate_person(age, name):
return PersonEntry.get(name = name, age = age)
我想一个更普遍的问题是,如果我有一个返回数据的函数,如何更新具有关系的模型?我是否在模型本身中有一个方法,或者我是否将它提升了一个级别(即将 update_books 移动到 Person 模型)我是 Django 新手,所以不太确定组织应该如何。