📜  filter vs get django (1)

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

Filter vs Get in Django

When working with Django, you may have come across situations where you need to retrieve data from the database based on specific criteria. In such cases, you can use either the filter() or get() methods in Django. However, it's important to understand the differences between these two methods and when to use them.

filter()

This method returns a QuerySet of objects that match the specified criteria. You can use it to retrieve multiple objects from the database that meet a specific condition. The syntax for using filter() is as follows:

queryset = MyModel.objects.filter(attribute=value)

Here, MyModel is the name of the model you want to retrieve objects from, attribute is the name of the field you want to filter on, and value is the value you want to filter by.

get()

This method is used to retrieve a single object from the database that meets a specific condition. The syntax for using get() is as follows:

object = MyModel.objects.get(attribute=value)

In this case, attribute and value have the same meaning as with filter(), but here, we're expecting only one object to be returned. If no object meets the condition specified, a DoesNotExist exception is raised. If more than one object meets the condition, a MultipleObjectsReturned exception is raised.

Examples

Let's say we have a Book model with the following fields:

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=50)
    genre = models.CharField(max_length=50)
    published_year = models.PositiveIntegerField()
  1. Retrieving all books of a specific genre using filter():
queryset = Book.objects.filter(genre='Mystery')
  1. Retrieving a single book with a specific title using get():
book = Book.objects.get(title='The Da Vinci Code')
Conclusion

In summary, filter() and get() are two useful methods in Django for retrieving data from the database based on specific criteria. Use filter() when you want to retrieve multiple objects that meet a specific condition, and use get() when you want to retrieve a single object that meets a specific condition. Remember that get() raises an exception if no object is found, or if more than one object is found.