📜  django is .get lazy - Python (1)

📅  最后修改于: 2023-12-03 15:30:28.615000             🧑  作者: Mango

Django is .get lazy - Python

When it comes to web development in Python, Django is one of the most popular frameworks out there. However, one interesting aspect of Django's ORM is its lazy evaluation through the .get method.

Lazy evaluation in Django

Lazy evaluation is a programming technique where the evaluation of an expression is delayed until its value is actually needed. In Django's ORM, this means that when you use the .get method to retrieve a single record from the database, the actual database query is not executed until you try to access one of the fields of the returned object.

For example, let's say you have a model called Person:

class Person(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()

    def __str__(self):
        return self.name

If you want to retrieve a person from the database with the name "John", you could do it like this:

john = Person.objects.get(name="John")

At this point, john is a Person object, but the database query to retrieve it has not been executed yet. Only when you try to access one of its fields, like john.age, will Django actually fetch the data from the database.

This can be very useful in situations where you might not need all the fields of an object, and you want to avoid fetching unnecessary data from the database.

Why is it called ".get lazy"?

The term "lazy" here comes from the fact that the query is not executed immediately, but only when needed. The .get method is called that way because it returns a single object, and it raises a DoesNotExist exception if there is no object that matches the query.

Conclusion

In this brief introduction, we've seen how Django's ORM provides lazy evaluation through the .get method. This can be a useful technique to optimize database queries and reduce the amount of unnecessary data fetching.