Django REST框架 - 使用信号

时间:2018-03-03 13:50:12

标签: python django rest

我是Django的新用户,想要使用OneToOne字段扩展我的用户模型(似乎最常推荐),我也有一个强制性的ManyToManyField。下面是我的models.py:

from django.db import models
from django.contrib.auth.models import User
from django.contrib.postgres.fields import ArrayField
from django.db.models.signals import post_save
from django.dispatch import receiver

class Config_Table(models.Model):

    entity_name = models.TextField(primary_key=True)
    category = models.TextField()
    description = models.TextField(blank=True,default='')

class Profile(models.Model):

    "The Profile of a user with details are stored in this model."

    user = models.OneToOneField(User, on_delete=models.CASCADE, max_length=11)

    # The default username is phone number (Ver. 1.0)

    phone_number = models.TextField(max_length=11,default=user)
    avatar = models.ImageField(default='../Static/1.jpeg')
    GENDER_CHOICES = (
        ('M','Male'),
        ('F','Female'),
    )
    gender = models.CharField(max_length=1,choices=GENDER_CHOICES)
    city = models.TextField(max_length=25)
    description = models.TextField(max_length=2000, blank=True, default='')
    interests = models.ManyToManyField(Config_Table)
    date_of_birth = models.DateField(auto_now_add=True)
    USER_TYPES = (
        ('User','Normal User'),
        ('Leader','Tour Leader'),
        ('Admin','Administrator'),
    )
    user_type = models.TextField(choices=USER_TYPES, default='User')
    join_date = models.DateTimeField(auto_now_add=True)
    official_docs = models.ImageField(default='../Static/1.jpeg')
    group_name = models.TextField(blank=True,default='')
    debit_card_number = models.IntegerField(blank=True, default=0)
    MUSIC_CHOICES = (
        ('Rock','Rock Music'),
        ('Trad','Traditional Music'),
        ('Elec','Electronic Music'),
        ('Clas','Classical Music')
    )
    favorite_music = ArrayField(models.TextField(null=True,default=''),size=2)

使用shell,我可以成功创建用户并分配如下所示的配置文件。表“Config_table”已填充了一些初始数据:

>>> user = User.objects.create_user(username='12345678900')
>>> test = Profile.objects.create(user=user,gender='M',city='NY',user_type='User',favorite_music=['Trad'])
>>> test.save
<bound method Model.save of <Profile: <django.db.models.query_utils.DeferredAttribute object at 0x7f9f98e8a080>>>
>>> test.interests.add('Ski')
>>> test.save
<bound method Model.save of <Profile: <django.db.models.query_utils.DeferredAttribute object at 0x7f9f98e8a080>>>

现在我想让我的观点更容易一些。那么,我发现HereHere我想使用post_save信号创建一个create_user方法,该方法用一行完成上述所有操作:

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance,gender=instance.gender,city=instance.city,user_type=instance.user_type,
                               favorite_music=instance.favorite_music)
        Profile.interests.add(instance.interests)


@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

但是当我尝试下面这样的时候。我收到错误:

user = User.objects.create_user(username='12345678900',gender='M',city='NY',interests='Ski',user_type='User',favorite_music=['Trad'])
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/amir/.virtualenvs/Django/lib/python3.6/site-packages/django/contrib/auth/models.py", line 150, in create_user
    return self._create_user(username, email, password, **extra_fields)
  File "/home/amir/.virtualenvs/Django/lib/python3.6/site-packages/django/contrib/auth/models.py", line 142, in _create_user
    user = self.model(username=username, email=email, **extra_fields)
  File "/home/amir/.virtualenvs/Django/lib/python3.6/site-packages/django/db/models/base.py", line 495, in __init__
    raise TypeError("'%s' is an invalid keyword argument for this function" % kwarg)
TypeError: 'gender' is an invalid keyword argument for this function

似乎我错过了一些非常明显或非常愚蠢的东西。有人可以帮忙吗?我在Ubuntu 16.04 LTS上使用Django 2.0.2和Postgres 10.1和Python 3.7。

编辑:我想要执行上述操作的原因是让用户的主键和配置文件的主键相同,而不是像下面这样。下面是我从第一个答案得到的样本(检查“id”和“user”字段):

>>> serial = ProfileSerializer(sample_profile,many=True)
>>> serial.data
[OrderedDict([('id', 13), ('first_name', ''), ('last_name', ''), ('phone_number', 'App.Profile.user'), ('avatar', '../Static/1.jpeg'), ('gender', 'M'), ('city', 'NY'), ('description', ''), ('date_of_birth', '2018-03-04'), ('user_type', 'User'), ('join_date', '2018-03-04T07:12:38.607959Z'), ('official_docs', '../Static/1.jpeg'), ('group_name', ''), ('debit_card_number', 0), ('favorite_music', ['Trad']), ('user', 18), ('interests', ['Ski'])])]

1 个答案:

答案 0 :(得分:0)

您的问题源于您的 post_save 信号 create_user_profile 不正确。 instance 变量是 django.contrib.auth.models.User 实例。 Profile 模型具有 gender 属性,而不是 django.contrib.auth.models.User 实例。你要做的主要是以下几点:

from django.contrib.auth.models import User
user = User.objects.get(pk=1)
print(user.gender)   # Does not exist

您已通过在其下创建User来扩展profile模型,但您尝试将User模型视为Profile模型,而不是from django.contrib.auth.models import AbstractUser class User(AbstractUser): USER = 0 LEADER = 1 ADMIN = 2 USER_TYPE_CHOICES = ( (USER, 'Normal User'), (LEADER, 'Tour Leader'), (ADMIN, 'Administrator'), ) user_type = models.IntegerField(choices=USER_TYPE_CHOICES, default=User.USER) # Your custom stuff here 模型

就个人而言,在我看来,您最好通过 extending Django's AbstractUser 创建自己的自定义用户模型。当您拥有各种不同类型的配置文件时,配置文件很有用,例如Facebook,Google,员工等具有不同属性的配置文件。我所看到的大多数内容应该足够普遍,可以使用自定义用户模型:

      <DataGrid AutoGenerateColumns="True" 
      SelectionUnit="Cell" 
      CanUserDeleteRows="True" 
      ItemsSource="{Binding Results}" 
      CurrentCell="{Binding CellInfo}"            
      SelectionMode="Single">

在开始编写用户模型之前,我建议考虑一下您的数据库设计。它将在未来为您节省很多麻烦。

[OFF主题]:此外,我想提一下,我在上面的示例中看到了 主要 问题模型。您似乎打算将借记卡号存储在数据库中。您的申请/组织必须遵循PCI DSS (Payment Application Data Security Standard)It is not something that you want to take lightly