django models.ForeignKey("Tablename) or models.Foreignkey(Tablenamevariable)

Viewed 73

Im looking at the django-generated model classes using inspectdb.

I noticed that sometimes strings and sometimes variable names are called based on their "read from top to bottom" appearance in the file.

here and example

class AuthGroup(models.Model):
    name = models.CharField(unique=True, max_length=150)

    class Meta:
        managed = True
        db_table = 'auth_group'


class AuthGroupPermissions(models.Model):
    id = models.BigAutoField(primary_key=True)
    group = models.ForeignKey(AuthGroup, models.DO_NOTHING)
    permission = models.ForeignKey('AuthPermission', models.DO_NOTHING)

    class Meta:
        managed = True
        db_table = 'auth_group_permissions'
        unique_together = (('group', 'permission'),)


class AuthPermission(models.Model):
    name = models.CharField(max_length=255)
    content_type = models.ForeignKey('DjangoContentType', models.DO_NOTHING)
    codename = models.CharField(max_length=100)

    class Meta:
        managed = True
        db_table = 'auth_permission'
        unique_together = (('content_type', 'codename'),)

Using a legacy db (mysql) in my case.

Quesion is: Can i not just always use the string name of the table insead of sometimes string sometimes variable? That would be safer in my case Would these two statements not do the same thing?

group = models.ForeignKey('AuthGroup', models.DO_NOTHING)
permission = models.ForeignKey('AuthPermission', models.DO_NOTHING)
1 Answers

Quesion is: Can i not just always use the string name of the table insead of sometimes string sometimes variable?

Yes: using ForeignKey(Foo, …) can be replaced with ForeignKey('Foo', …). A string literal is often used to refer to a model that will be defined further in the file, since you can not use Foo if the Foo class is not yet defined.

But if you want, you can use string literals for all the ForeignKeys. You can refer to a model with 'app_name.ModelName' or with simply 'ModelName' if the model is defined for the same app name as the model you are defining.

Related