Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: correct order of these models

I have these models in my app models.py:

class A(models.Model):
    #some details
    pass


class B(models.Model):
    a = models.ForeignKey(A, null=True, blank=True)
    c = models.ForeignKey(C, null=True, blank=True)

class C(models.Model):
    pass

    def method(self):
        b_list = B.objects.filter(c=self)
        a_list = []
        for b in b_list:
            a_list.append(b.a)

        return a_list

this gives me an error when i launch the webserver because in B it declares that C is not defined.

then if i put these models in order A C B django tells me that B is not defined in C's method().

How can i resolve this "not defined" issue in this situation? it seems circular!

like image 578
apelliciari Avatar asked Nov 27 '25 13:11

apelliciari


1 Answers

You can always use a string in such cases:

class A(models.Model):
    #some details
    pass


class B(models.Model):
    a = models.ForeignKey("A", null=True, blank=True) # note the quotes
    c = models.ForeignKey("C", null=True, blank=True) # note the quotes

class C(models.Model):
    pass

If this was a more "extreme" case and you couldn't use this trick, declaring C first, then A and B, and after that C.method (def C_method [...] C.method = C_method) would have been the way to follow.

like image 180
Gabi Purcaru Avatar answered Nov 30 '25 02:11

Gabi Purcaru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!