Recommended for get_or_new

Since the state of users is often managed using RDB in Web services, I see code in various projects such as creating records if they are not acquired at the time of acquisition.

Django also has a standard method called get_or_create that retrieves (SELECT) a table record if it exists, and creates a record (INSERT) if it doesn't.

For example, if you want to display the point balance for each user on the sweepstakes site, the default value is 0 points if there is no user record.

If not, the move to create a record is to save this 0 point information in a ** purposely ** table.

** Do I need to save the default values? ** **

Besides, creation (INSERT) is ** update processing **. It is necessary to consider various things such as exclusive control and double execution when updating. Locks are also created by INSERT.

However, it will be difficult to write the process because you cannot get an instance of the model with just get.

** So get_or_new **

If not, create get_or_new that creates only an instance and does not create a record. This will allow you to get an instance without any side effects.

The code looks like this

# models.py
from django.db import models


class User(models.Model):
    point = models.IntegerField('Earned points', default=0)
    
    @classmethod
    def get_or_new(cls, pk):
        try:
            return cls.objects.get(pk=pk)
        except cls.DoesNotExist:
            return cls(pk=pk)


# view.py
from django.views.generic import TemplateView
from .models import User


class IndexView(TemplateView):
    template_name = "index.html"
    def get(request, user_id):
        user = User.get_or_new(user_id)
        self.render_to_response({'user': user})


This will take the required instance of User and, of course, will return 0 as user.point. There are other benefits

etc. Please note that the update process should not be performed based on the data obtained from get_or_new. If you do it twice, the wrong data will eventually be written.

This time it's a reference story, so I'll write an update story next time.

Recommended Posts

Recommended for get_or_new
Linux distribution recommended for beginners
Recommended container image for Python applications
Recommended competition site for data scientists
[Recommended tagging for machine learning # 4] Machine learning script ...?
Recommended study order for machine learning / deep learning beginners
For new students (Recommended efforts for Python beginners Part 1)