The purpose of using a custom manager to create objects using django?

I see in the Django documentation:

Link to Model Instance: Creating Objects

You may be tempted to customize the model by overriding the __init__ method. However, if you do, try not to change the signature of the call, since any change may interfere with the preservation of the model instance.
Instead of overriding __init__ , try using one of these approaches:

  • Add the class class to the model class.
  • Add method to user manager (usually preferred)

Why is the second solution “usually preferable”?

In a situation where I have a model B that extends model A through a OneToOne relationship, and I want to create a method that generates an object B that generates the corresponding object A as well as it’s “better” to use the user manager as suggested, given that I probably will not use this manager for anything other than what is provided by the default manager?

+4
source share
1 answer

I think this is preferable because it looks cleaner in code. You can also read in underscores too much, since the advantage or difference is not so great. However, when implementing things, I use the proposed approach.

Consider the following model (purely for illustrative purposes):

 class Vehicle(models.Model): wheels = models.IntegerField() color = models.CharField(max_length=100) 

In your application you often need to get all the cars, or all the motorcycles, or some type of vehicle. To hold DRY stuff, you need a standard form for retrieving this data. Using class methods, you get the following:

 class Vehicle(models.Model): #(...) @classmethod def cars(cls): return Vehicle.objects.filter(wheels=4) cars = Vehicle.cars() green_cars = Vehicle.cars().filter(color='green') 

If you create a manager, you will get something like this:

 class CarManager(models.Manager): def get_query_set(self): return super(CarManager, self).get_query_set().filter(wheels=4) class Vehicle(models.Model): #(...) car_objects = CarManager() cars = Vehicle.car_objects.all() green_cars = Vehicle.car_objects.filter(color='green') 

In my opinion, the latter looks cleaner, especially when the situation becomes more complicated. It saves clutter from your model definitions and saves something similar to using the objects manager by default.

+4
source

Source: https://habr.com/ru/post/1495948/


All Articles