Django Model Method with Native Instance

I am trying to move some functional logic into a model method (and not into views), where, in my opinion, this belongs to:

class Spans(models.Model): snow = models.IntegerField() wind = models.IntegerField() exposure = models.CharField(max_length=1) module_length = models.IntegerField() max_roof_angle = models.IntegerField() building_height = models.IntegerField() importance_factor = models.IntegerField() seismic = models.DecimalField(max_digits=4, decimal_places=2) zone = models.IntegerField() profile = models.CharField(max_length=55) tilt_angle = models.IntegerField() span = models.DecimalField(max_digits=18, decimal_places=15) def get_spans(self, snow_load, wind_speed, module_length): """ Function to get spans. """ spans = self.objects.filter( snow=snow_load, wind=wind_speed, exposure='B', module_length__gte=module_length, max_roof_angle=45, building_height=30, importance_factor=1, seismic=1.2, zone=1, profile='worst' ).order_by('snow', 'module_length', 'span') return spans 

However, I'm a little unsure of what to call it. In the shell, I tried:

 >>> possible_spans = Spans.get_spans(0, 85, 54) 

or

 >>> possible_spans = Spans.get_spans(Spans, 0, 85, 54) 

but I get an error:

 TypeError: unbound method get_spans() must be called with Spans instance as first argument (got int instance instead) 

or

 TypeError: unbound method get_spans() must be called with Spans instance as first argument (got ModelBase instance instead) 

I know that I am missing something fundamental in python logic, but I'm not sure what it is.

Any help would be greatly appreciated.

+2
source share
1 answer

The method must be called either with an instance, as a method call, which makes it self-arg by default. For instance,

 instance = Spans.objects.get(id=1) instance.get_spans(0, 85, 54) 

Or if you want to call using the class itself. You will need to transfer the instance manually

 instance = Spans.objects.get(id=1) Spans.get_spans(instance, 0, 85, 54) 

Update: What you are looking for can be achieved using the static method

 @staticmethod def get_spans(snow_load, wind_speed, module_length): """ Function to get spans. """ spans = Spans.objects.filter( snow=snow_load, wind=wind_speed, exposure='B', module_length__gte=module_length, max_roof_angle=45, building_height=30, importance_factor=1, seismic=1.2, zone=1, profile='worst' ).order_by('snow', 'module_length', 'span') return spans 

Now you can directly,

 Spans.get_spans(0, 85, 54) 
+4
source

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


All Articles