Django如何从外部api数据更新模型对象字段

时间:2019-12-12 18:39:43

标签: python django database api django-models

我有一个在调度程序上运行的脚本,用于从api获取数据,然后打算使用此数据更新当前数据库模型信息。

我的模型 ShowInfo 在main / models.py中:

from django.contrib.auth.models import User

class ShowInfo(models.Model):
    title = models.CharField(max_length=50)
    latest_ep_num = models.FloatField()
    ld = models.BooleanField()
    sd = models.BooleanField()
    hd = models.BooleanField()
    fhd = models.BooleanField()
    following = models.ManyToManyField(User, related_name = 'following', blank=True)

我设法将问题隔离到脚本的这一部分,该部分可以运行,但是将重复的具有相同标题的节目插入数据库:

    else: #test if api fails
        for t in real_title:
            if t in data_title:  #testing if the titles in the database and from the api match
                a = ShowInfo.objects.get(title=t)
                id = a.id
                b = next(item for item in show_list if item["title"] == t)
                a1 = ShowInfo(id = id, title = b["title"], latest_ep_num=b["latest_ep_num"], ld=b["ld"], sd=b["sd"],hd=b["hd"],fhd=b["fhd"])
                a1.save()

有关列表的一些其他信息(其中 show_list 是从api获取的词典列表):

database = ShowInfo.objects.values()
real_title = []
data_title = []

for show in show_list:
    real_title.append(show["title"])
for data in database:
    data_title.append(data["title"])

脚本运行时,我注意到使用DB Browser for SQLite浏览数据库时发现对象被插入,而不是我想要的更新

该脚本应该从api和数据库中捕获具有相同标题的节目,并更新所有更改的信息。有人知道我的 save()方法有什么问题吗?

1 个答案:

答案 0 :(得分:0)

经过一天的反复试验和搜寻,我终于找到了对我有用的解决方案。

对于感兴趣的任何人,this is the solution是我从Stack上的另一个用户那里发现的,该用户利用重写内部保存方法来强制更新,并且如果数据库中已经存在具有相同字段的当前对象,则不插入。

>

在我的情况下,其他方法(例如执行force_update=Trueupdate_or_create()无效)。