Saturday, January 4, 2020

Abhijeet Pal: Adding Custom Model Managers In Django

A manager is an interface through which database query operations are provided to Django models. At least one Manager exists for every model in a Django application, objects is the default manager of every model that retrieves all objects in the database. However, one model can have multiple model managers, we can also build our own custom model managers by extending the base manager class. In this article, we will learn how to create custom model managers in Django. Creating Custom Model Managers In this article, we will build a model manager for a blog application. class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=False) def __str__(self): return self.title As we know objects is the default model manager for every model, therefore Post.objects.all() will return all post objects. The objects method is capable of doing all basic QuerySets then why would we need a custom model manager? There are two reasons you might want to customize a Manager – To add extra Manager methods. To modify the initial QuerySet the Manager returns. Let’s …

The post Adding Custom Model Managers In Django appeared first on Django Central.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...