Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在django模型上只存储一个值?_Python_Django_Django Models - Fatal编程技术网

Python 如何在django模型上只存储一个值?

Python 如何在django模型上只存储一个值?,python,django,django-models,Python,Django,Django Models,下面是我的模型 from django.db import models LEVEL_CHOICES = (('beg','beginner'),('ind','inter'),('exp','expert')) class scrap(models.Model): subject = models.CharField(max_length=128,unique=True) # level= models.CharField(max_length=128,unique=True)

下面是我的模型

from django.db import models
LEVEL_CHOICES = (('beg','beginner'),('ind','inter'),('exp','expert'))
class scrap(models.Model):
    subject = models.CharField(max_length=128,unique=True)
    # level= models.CharField(max_length=128,unique=True)
    level = models.CharField(max_length=128, choices=LEVEL_CHOICES)
    time = models.IntegerField(unique=True)

def __str__(self):
        return self.subject

是否仍然存在这样的情况,即每个类只能存储一个值。我所做的是通过窗体向此模型的对象提供值。因此,我只需要此类的一个实例。如果通过窗体提供另一个值,我想要的是替换旧的值和存储新的值。

我不确定为什么要为模型保留一个对象,但这很容易实现:

if scrap.objects.exists():
    current_scrap = Scrap.objects.all()[0]
else:
    current_scrap = Scrap()
current_scrap.subject = new_subject
current_scrap.level = new_level
current_scrap.time = new_time
current_scrap.save()

没用。我实际上是django的新手,我不知道我应该把代码放在上面的什么地方?