Search code examples
django-modelsdjango-4.0

What does it mean "to=" when creating model field in django?


Are those tree ways giving the same result/field, is there any other way?

    class Message(models.Model):
        user = models.ForeignKey(to=User)
        user = models.ForeignKey(User)
        user = models.ForeignKey("User")

Solution

  • Are those tree ways giving the same result/field

    Yes, although the first requires to import a model named user, and is thus vulnerable to cyclic imports.

    is there any other way?

    The advised way is to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly, so:

    from django.conf import settings
    
    
    class Message(models.Model):
        user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

    For more information you can see the referencing the User model section of the documentation.