[Django]-Django model method with self instance

4👍

Method needs to be called either with the instance, as the method call makes it as the default self arg. For example,

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

Or if you can want to call using class itself. You would have to pass the instance manually

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

Update:
What you are looking for could be achieved using a 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 could directly do,

Spans.get_spans(0, 85, 54)

0👍

I arrived here with the same problem (I know it’s an old question).

After some research this is how I proceeded:

  • I consider get_spans a class method (because it needs to access a class attribute of the same class: Spans.objects)
  • Implementation:
    1. Apply @classmethod decorator
    2. Use cls as first method parameter
    3. Call the other method as cls.objects.filter.

Would look like this:

@classmethod # Steps 1 & 2
def get_spans(cls,snow_load, wind_speed, module_length):
        """
        Function to get spans.
        """
        # Step 3
        spans = cls.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
👤Martin

Leave a comment