gpt4 book ai didi

django - 如果此 RECORD 不存在,则保存它?

转载 作者:行者123 更新时间:2023-12-04 07:00:22 26 4
gpt4 key购买 nike

模型.py

#.....
class FilterSave(models.Model):
def __unicode__(self):
return "%s" % (self.name)
name = models.CharField(max_length=50)
customer_type = models.CharField(max_length=20)
tag = models.CharField(max_length=10)

在我的 views.py 中
#......
def save_filter(self, filter_name, keyword_filter):
dict_json = eval(json.dumps(keyword_filter))
filter_saves = FilterSave.objects.all()
# Avoid record that already exist
filter_save = FilterSave(name=filter_name, customer_type=dict_json["customer_type"], tag=dict_json["tag"])

# I am trying ....
for fs in filter_saves:
if fs.name != filter_name:#just check for a field name
filter_save.save()
else:
print 'already exist '

我试过的更多

# 避免名称冲突(仅用于名称字段而不用于记录)
filter_save = FilterSave(name=filter_name, customer_type=dict_json["customer_type"], tag=dict_json["tag"])
exists = FilterSave.objects.filter(name=filter_name)
if not exists:
filter_save.save()

我的问题在这里。如果表中不存在记录,我想保存它。任何人都可以帮助我在这里尝试什么?
谢谢

最佳答案

Django 有一个方便的方法 get_or_create(defaults=None, **kwargs)

get_or_create

A convenience method for looking up an object with the given kwargs (may be empty if your model has defaults for all fields), creating one if necessary.

Returns a tuple of (object, created), where object is the retrieved or created object and created is a boolean specifying whether a new object was created.


你是这个意思吗?

关于django - 如果此 RECORD 不存在,则保存它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1968659/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com