Using Django auth User model as a Foreignkey and reverse relations

后端 未结 3 1313
傲寒
傲寒 2021-02-08 01:09

I am using the User model from django.contrib.auth.models. I have another model called Post which references User through a

相关标签:
3条回答
  • 2021-02-08 01:37

    it may be caused by you defined related_name option in ForeignKey (or OneToOneField), if it's like this :

    user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name='post')
    genre = models.CharField(max_length=100)
    

    you should use it as below :

    print(user.post.genre)
    

    Or :

    print(post.user.email)
    

    Notice : if i can see your models.py and settings.py it would be better answer.

    0 讨论(0)
  • 2021-02-08 01:54
    Post.objects.filter(user=request.user).order_by('-timestamp')
    
    0 讨论(0)
  • 2021-02-08 01:55

    Have you included the application containing the Post model in your settings.py installed apps?

    e.g.

    INSTALLED_APPS = (
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.sites',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'testapp'
        # Uncomment the next line to enable the admin:
        # 'django.contrib.admin',
        # Uncomment the next line to enable admin documentation:
        # 'django.contrib.admindocs',
    )
    

    and ran manage.py syncdb?

    python manage.py syncdb
    

    i.e does the database table for the Post model definately exist?

    I did a quick test and found no problems:

    from django.db import models
    from django.contrib.auth.models import User
    
    class PostModel(models.Model):
        user = models.ForeignKey(User)
    
    (test) C:\Users\Steven\django_projects\test\testproj>python manage.py shell
    Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    (InteractiveConsole)
    >>> from django.contrib.auth.models import User
    >>> test = User.objects.get(username='test')
    >>> test.postmodel_set.all()
    []
    
    0 讨论(0)
提交回复
热议问题