Search code examples
pythondjangodjango-modelsdjango-usersdjango-database

ForeignKey to a Model field?


I want a foreign key relation in my model with the username field in the User table(that stores the user created with django.contrib.auth.forms.UserCreationForm).

This how my model looks:

class Blog(models.Model):
    username = models.CharField(max_length=200) // this should be a foreign key
    blog_title = models.CharField(max_length=200)
    blog_content = models.TextField()

The username field should be the foreign key.The Foreign Key should be with this field


Solution

  • You can't have an ForeignKey to a field, but you can to a row.

    You want username which is available through the User model

    So:

    blog.user.username
    

    If you insist on having blog.username you can define a property like this:

    from django.db import models
    from django.contrib.auth.models import User
    
    class Blog(models.Model):
        user = models.ForeignKey(User)
    

    Then to access the field you want use:

    blog.user.username
    

    If you insist on having blog.username you can define a property like this:

    from django.db import models
    from django.contrib.auth.models import User
    
    class Blog(models.Model):
        user = models.ForeignKey(User)
    
        @property
        def username(self):
            return self.user.username
    

    With that property, you can access username through blog.username.

    Note on how to import User

    user = ForeignKey('auth.User')
    

    or

    from django.contrib.auth.models import User
    user = ForeignKey(User)
    

    or the more recommended

    from django.conf import settings
    user = ForeignKey(settings.AUTH_USER_MODEL)