Understanding the difference between .get and .first in Django

Posted on Fri 21 May 2021 in Better Django

Photo

When retrieving a single record in Django, the ORM offers two possible methods: .get() and .first(). Let's learn how each one works and when to use them.

Get

Django's most basic way to retrieve a single record is the .get() method. It is used as follows:

burger = Menu.objects.get(name="Beef Burger")

Quick facts about .get():

  • It retrieves only one record.

  • If no record exists that meets the given criteria, it raises a DoesNotExist exception.

  • If more than one record with the given criteria exists, it raises a MultipleObjectsReturned exception.

First

A different way to get one record is …


Continue reading

Write better Django views

Posted on Fri 12 March 2021 in Better Django

image

Should you use class-based views (CBV's) or function-based views (FBV's) in Django? It seems a lot of people are pushing CBV's, touting them to be the "standard" way of writing views in Django. But why do FBV's still exist then? Just for backward-compatibility? This is my highly opinionated "view" (see what I did there??) on this matter.

The topic is hotly debated. Why are some people so passionate about CBV's? CBVs are said to be better because they abstract a lot of boiler-plate code into base classes and mixins. This is true. As a very basic example, instead of writing …


Continue reading

Learn the subtle differences between Save and Update in Django

Posted on Fri 12 February 2021 in Better Django

To save data in Django, you normally use .save() on a model instance. However the ORM also provides a .update() method on queryset objects. So which one should you use? Let's take a look at each, and then decide which one to use in which situations.

Save

The .save() method is used to write a model instance to the database. It can be an existing record or even a new one. For an existing record, Django will run a SQL UPDATE statement on the database. For a new record, Django will run an INSERT. Before Django 3.0, it would …


Continue reading

Speed up bulk-exists check with python sets

Posted on Sat 01 August 2020 in Better Django

image

The .exists() function of Django's ORM is very useful. However, if you need to do this in bulk (think hundreds of thousands or more), this becomes a strain on your database. Let's say you are fetching records from an external system, and if the record doesn't exist locally, you need to do something:

for item in external_records:
    if not Data.objects.filter(external_id=item.id).exists():
        # Do something

If you are working with a large quantity of records, this will flood your DB with queries. Instead, you could first pull all external_id values from the DB:

existing_ids = Data.objects.all …

Continue reading