Search code examples
pythondjangomodels

Ordering Django models.py alphabetically : refering to a model defined below


Quick question,

I was trying to cleanup my models.py that was a bit all over the place; figured that ordering them alphabetically would be smart...

Problem Some models refer to other models (via Foreign Keys) that are now defined below them in the file.

I'm sure it's a easy fix, what should i do ?

from django.db import models


class Craft(models.Model):
    subdpt = models.ForeignKey(Subdepartment, on_delete=models.CASCADE)
    #### UNDEFINED NAME SUBDEPARTMENT ###

    title = models.CharField(max_length = 200)
    description = models.CharField(max_length = 200, blank = True)

    def __str__(self):
        return self.title

class Subdepartment(models.Model):
    subdpt_name = models.CharField(max_length=200)

    def __str__(self):
        return self.subdpt_name

    class Meta:
        permissions = (
            ("can_add", "Can add items in app"),
            ("can_edit", "Can edit items in app"),
        )

Solution

  • You can always specify the related model name as a string:

    subdpt = models.ForeignKey('Subdepartment', on_delete=models.CASCADE)