我有一个django模型。我需要获得username
和password
。但那时我想通过vk()
类处理它们以获取uid
,token
,secret
并使用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
答案 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)