Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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() 
like image 986
Joff Avatar asked Dec 16 '15 07:12

Joff


People also ask

WHAT IS models ForeignKey?

ForeignKey is a Django ORM field-to-column mapping for creating and working with relationships between tables in relational databases.

How do I reference a user model in Django?

Referencing the User model Instead of referring to User directly, you should reference the user model using django. contrib. auth. get_user_model() .

Why we use ForeignKey in Django models?

What is ForeignKey in Django? ForeignKey is a Field (which represents a column in a database table), and it's used to create many-to-one relationships within tables. It's a standard practice in relational databases to connect data using ForeignKeys.

What is the difference between ForeignKey and OneToOneField?

The only difference between these two is that ForeignKey field consists of on_delete option along with a model's class because it's used for many-to-one relationships while on the other hand, the OneToOneField, only carries out a one-to-one relationship and requires only the model's class.


1 Answers

Don't use the User model directly.

From the documentation

Instead of referring to User directly, you should reference the user model using django.contrib.auth.get_user_model()

When you define a foreign key or many-to-many relations to the user model, you should specify the custom model using the AUTH_USER_MODEL setting.

Example:

from django.conf import settings from django.db import models  class Article(models.Model):     author = models.ForeignKey(         settings.AUTH_USER_MODEL,         on_delete=models.CASCADE,     ) 
like image 50
Andrew E Avatar answered Oct 02 '22 20:10

Andrew E