【问题标题】:Django-rest-auth using user objectDjango-rest-auth 使用用户对象
【发布时间】:2016-07-14 04:31:05
【问题描述】:

我有一个 django 项目,我在其中使用 django-rest-auth 对用户进行身份验证。我的settings.py:

INSTALLED_APPS = (
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'rest_framework',
 #following was added to allow cross domain requests
 'corsheaders',
 #following were added for ssl thing
 'djangosecure',
 'sslserver',
 #following were added for authentication
 'rest_framework.authtoken',
 'rest_auth',
 'allauth',
 'allauth.account',
 'rest_auth.registration',
 'demo',
)

我有两个模型:ExerciseRating。我没有创建 User 模型,因为它必须由 django-rest-auth / django.contrib.auth 提供。 用户可以对特定练习给予多个评分。

我的 models.py 如下所示:

class Exercise(models.Model):

#Field for storing exercise type
EXERCISE_TYPE_CHOICES = (
    (1, 'Best stretch'),
    (2, 'Butterfly reverse'),
    (3, 'Squat row'),
    (4, 'Plank'),
    (5, 'Push up'),
    (6, 'Side plank'),
    (7, 'Squat'),
)
exercise_type = models.IntegerField(choices=EXERCISE_TYPE_CHOICES)

#Field for storing intensity level
INTENSITY_LEVEL_CHOICES = (
    (1, 'Really simple'),
    (2, 'Rather Simple'),
    (3, 'Simple'),
    (4, 'Okay'),
    (5, 'Difficult'),
    (6, 'Rather Difficult'),
    (7, 'Really Difficult'),
)

intensity_level = models.IntegerField(choices=INTENSITY_LEVEL_CHOICES)
#Field for storing video url for a particular exercise
video_url = models.URLField()
#Field for storing description of the exercise
description = models.CharField(max_length=500)


class Rating(models.Model):

#Field for storing exercise type
exercise = models.ForeignKey(Exercise, related_name='ratings', blank=True, null=True)
#Field for storing rating
RATING_CHOICES = (
    ('H', 'Happy'),
    ('N', 'Neutral'),
    ('S', 'Sad'),
)
value = models.CharField(max_length=1,choices=RATING_CHOICES)   

根据上面的描述,我的 Rating 模型还应该包含 userid 作为外键以及 exerciseid , 正确的?

我怎样才能做到这一点?如何修改我的评分模型?我需要导入什么?

【问题讨论】:

    标签: django django-models django-rest-auth


    【解决方案1】:
    from django.contrib.auth.models import User
    
    class Rating(models.Model):
        user = models.ForeignKey(User)
        # other fields
    

    我认为这就是您要寻找的。 Here 是一个我认为与您的问题有关的例子

    【讨论】:

    • 但是,不应该是外键而不是oneTooneField吗?
    • 对不起。我的错。我很快就阅读了您的问题,并认为您的问题是如何在模型中添加与用户对应的字段。我会修改答案。
    猜你喜欢
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    • 2020-05-21
    • 2020-02-28
    • 2019-07-10
    • 2020-01-12
    • 1970-01-01
    相关资源
    最近更新 更多