Search code examples
pythondjangomodels

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.

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.

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.


Solution

  • 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.