Search code examples
pythondjangodjango-modelsforeign-keys

foreignkey (user) in models


I read the docs and this post... Django - Foreign Key to User model

I followed what it said and I still cannot get it to work. When I try to run the migrations I get this error in the traceback...

django.db.utils.ProgrammingError: column "author_id" cannot be cast automatically to type integer
HINT:  You might need to specify "USING author_id::integer".

I just don't know how to go about fixing that error.

from django.db import models
from django.contrib.auth.models import User

# Create your models here.
class BlogCategory(models.Model):
    '''model for categories'''

    title = models.CharField(max_length=30)
    description = models.CharField(max_length=100)


class BlogPost(models.Model):
    '''a model for a blog post'''

    author = models.ForeignKey(User)
    date = models.DateField()
    title = models.CharField(max_length=100)
    post = models.TextField()

Solution

  • I do not know the "settings.AUTH_USER_MODEL" approach but a well-known approach and commonly used is the "Auth.User" model. Something like this on your end.

    from django.contrib.auth.models import User
    
    class BlogPost(models.Model):
        '''a model for a blog post'''
    
        author = models.ForeignKey(User)
        date = models.DateField()
        title = models.CharField(max_length=100)
        post = models.TextField()