Django - 保存前处理模型数据

时间:2017-06-20 06:44:24

标签: python django

我有一个django模型。我需要获得usernamepassword。但那时我想通过vk()类处理它们以获取uidtokensecret并使用vk()类中的字段保存模型。我该怎么办?

from django.db import models
from vk_class import vk

class data(models.Model):

    # that's what I ask for
    username = models.CharField(max_length=50)
    password = models.CharField(max_length=50)

    # that's only what I want to save
    uid = vk(username=username, password=password).uid
    token = vk(username=username, password=password).token
    secret = vk(username=username, password=password).secret

1 个答案:

答案 0 :(得分:0)

评论后更新
您可以使用editable=False为此字段和自定义管理员重载objects.create https://docs.djangoproject.com/en/1.11/topics/db/managers/#custom-managers

from django.db.models.signals import post_save
from django.dispatch import receiver
from django.db import models

class DataQuerySet(models.QuerySet):
    def create(self, username, password, *args, **kwargs):
        vk_data = vk(username=username, password=password)
        kwargs.update({
            'uid': vk_data.uid,
            'token': vk_data.token,
            'secret': vk_data.secret
        })
        return self.create(*args, **kwargs)

class data(models.Model):
    # that's only what I want to save
    uid = models.CharField(max_length=256, blank=True, editable=False)
    token = models.CharField(max_length=256, blank=True, editable=False)
    secret = models.CharField(max_length=256, blank=True, editable=False)

    objects = DataQuerySet.as_manager()

然后在代码中

data_obj = data.objects.create(username, password)