django foreignkey(user) in models

后端 未结 4 1122
臣服心动
臣服心动 2020-12-31 00:23

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

相关标签:
4条回答
  • 2020-12-31 00:51

    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()
    
    0 讨论(0)
  • 2020-12-31 00:56

    the column "author_id" doesn't exist, looks like is the same problem from here : Django suffix ForeignKey field with _id , so to avoid this traceback you may use :

    author = models.ForeignKey(User, db_column="user")
    
    0 讨论(0)
  • 2020-12-31 00:58

    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,
        )
    
    0 讨论(0)
  • 2020-12-31 01:10

    If you created a custom User model, you would use setting.AUTH_USER_MODEL, if not you can go ahead an use User model

    Referencing Django User model

    0 讨论(0)
提交回复
热议问题