简体   繁体   English

Django:更新模型的正确方法

[英]Django: Proper Way to Update Models

Suppose I have the following function, which retrieves data from a server in the form of user-defined objects. 假设我具有以下功能,该功能以用户定义的对象的形式从服务器检索数据。 For example, let's define the objects as PersonalEntry. 例如,让我们将对象定义为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, 

Both user-defined classes has an .as_dict() method which returns all its attributes in a dictionary. 这两个用户定义的类都有一个.as_dict()方法,该方法在字典中返回其所有属性。

I would like to update the model whenever this function is called (ie. update the fields if the instance of that model already exists, else, define a new instance of the model). 每当调用此函数时,我都想更新模型(即,如果该模型的实例已经存在,则更新字段,否则,定义模型的新实例)。 This is my current setup. 这是我当前的设置。

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)

I suppose a more general question is, how do I update models with relationships if I have a function which returns data? 我想一个更笼统的问题是,如果我有一个返回数据的函数,该如何用关系更新模型? Do I have a method in the model itself, or do I have it one level up (ie. move update_books to the Person model) I'm new to Django, so not really sure how the organization should be. 我是模型本身中的一种方法,还是将它向上一级(即,将update_books移至Person模型),我是Django的新手,所以不确定该如何组织。

I confess I haven't completely grokked your question, but I'll take a punt that you should look into 我承认我还没有完全解决您的问题,但是我会建议您研究一下

Managers

Generally, in django, everything is done as lazily as possible - meaning nothing gets updated until you actually try to use it - so you don't update models/relationships as you go, rather you just declare what they are (perhaps with a manager) then it works it out the current value only when asked. 通常,在django中,所有事情都尽可能地懒惰地完成-意味着什么都不会更新,直到您实际尝试使用它为止-因此您不会在进行过程中更新模型/关系,而只是声明它们是什么(也许与经理联系) ),则仅在询问时才计算出当前值。

Methods returning a collection (or queryset) of some kind of a model, should be a part of the Managers . 返回某种模型的集合(或查询集)的方法应该是Manager的一部分。 So in your case update_books should be in a custom manager for BookEntry and update_persons should be in custom manager for PersonEntry . 所以你的情况update_books应该是一个自定义的经理BookEntryupdate_persons应在自定义的经理PersonEntry

Also do not call the function retrieve_* from inside the model or manager. 也不要从模型或管理器内部调用函数retrieve_* Call it in your application logic and then pass the result to the manager method unless that method itself is part of the manager/model. 在应用程序逻辑中调用它,然后将结果传递给manager方法,除非该方法本身是manager / model的一部分。

You do not need a separate filter and update method. 您不需要单独的filterupdate方法。 Depending on how you have retrieved the data and it has a pk you can directly do a save . 根据您检索数据的方式及其是否包含pk ,可以直接进行save See How Does Django Know when to create or update 请参阅Django如何知道何时创建或更新

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM