在Django中保存Google凭据:对用户使用ForeignKey或OneToOneField?

时间:2018-08-14 18:51:52

标签: python django google-api

我正在按照https://developers.google.com/api-client-library/python/auth/web-app上提供的Flask示例,在Django网络应用中实现Google OAuth2授权流程。我正要实现将凭据保存到持久数据库而不是会话的操作项(在注释中提到)。

我注意到有一些示例Django项目使用了Google弃用的oauth2client。来自https://github.com/google/google-api-python-client/blob/master/samples/django_sample/plus/models.py的一个示例是:

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

from oauth2client.contrib.django_util.models import CredentialsField


class CredentialsModel(models.Model):
  id = models.ForeignKey(User, primary_key=True)
  credential = CredentialsField()

我在问id应该是ForeignKey,还是OneToOneField更合适?到目前为止,这是我的改编:

from django.db import models
from django.contrib.postgres.fields import ArrayField
from .timestamped_model import TimeStampedModel
from .user import User


class GoogleCredentials(TimeStampedModel):
    """
    Model for saving Google credentials to a persistent database (cf. https://developers.google.com/api-client-library/python/auth/web-app)
    The user's ID is used as the primary key, following https://github.com/google/google-api-python-client/blob/master/samples/django_sample/plus/models.py.
    (Note that we don't use oauth2client's CredentialsField as that library is deprecated).
    """
    id = models.ForeignKey(
        User,
        primary_key=True,
        limit_choices_to={'is_staff': True},
        # Deleting a user will automatically delete his/her Google credentials
        on_delete=models.CASCADE)
    token = models.CharField(max_length=255)
    refresh_token = models.CharField(max_length=255)
    token_uri = models.CharField(max_length=255)
    client_id = models.CharField(max_length=255)
    client_secret = models.CharField(max_length=255)
    scopes = ArrayField(models.CharField(max_length=255)) 

但是,当我迁移时,我从Django得到以下警告:

System check identified some issues:

WARNINGS:
lucy_web.GoogleCredentials.id: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOneField.
    HINT: ForeignKey(unique=True) is usually better served by a OneToOneField.

在这种情况下,使用OneToOneField会更好吗?这意味着用户只能拥有一组凭据。

0 个答案:

没有答案