假設我有以下函數,它以用戶定義對象的形式從服務器檢索數據。例如,我們將對象定義爲PersonalEntry。Django:更新模型的正確方法
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的新手,所以不太確定組織應該如何。