Search code examples
pythondjangomodels

Django models definition ordering


For example, I have 2 models: Model1 and Model2. Model1 has field ForeignKey(Model2). Model2 has method, that returns all instances of Model1 which has this instance of Model2 as ForeignKey.

But it doesn't work, because Model2 is defined after Model1 and it knows nothing about Model2. How to solve this problem?


Solution

  • Take a look at the django docs. You can specify the model using a string so it evaluates later: https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey

    class Car(models.Model):
        manufacturer = models.ForeignKey('Manufacturer')
        # ...
    
    class Manufacturer(models.Model):
        # ...