2

I have the following two Django Classes MyClassA and MyClassB.

MyClassB has a foreign key reference to an instance of MyClassA.

from django.db import models

class MyClassA(models.Model):
    name = models.CharField(max_length=50, null=False)

    @classmethod
    def my_method_a(cls):
        # What do I put here to call MyClassB.my_method_b()??


class MyClassB(models.Model):
    name = models.CharField(max_length=50, null=False)
    my_class_a = models.ForeignKey(MyClassA, related_name="MyClassB_my_class_a")

    @staticmethod
    def my_method_b():
        return "Hello"

From within MyClassA's class method my_method_a, I would like to call MyClassB's static method my_method_b. How can I do it? If my_method_a was an instance method, I would simply do self.MyClassB_my_class_a.model.my_method_b(). But since I don't have an instance of MyClassA, I don't know how to do it.

Can I use cls instead of self?

Saqib Ali
  • 11,931
  • 41
  • 133
  • 272

1 Answers1

1

Since it is a staticmethod, you don't need an instance.

You can call MyClassB.my_method_b() directly.

wim
  • 338,267
  • 99
  • 616
  • 750
  • In `my_method_a()`, it doesn't know about `MyClassB`. They are in separate files. Can I use the `related_name` field to get from `my_method_a()` to `my_method_b()`? – Saqib Ali Sep 15 '16 at 23:45
  • So what? Just import MyClassB. If you don't want to do that for some reason, you can use [`get_model(app_label, model_name='MyClassB')`](https://docs.djangoproject.com/en/1.10/ref/applications/#django.apps.AppConfig.get_model) instead. – wim Sep 15 '16 at 23:55