社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Django

在update或create django中标识更新的字段

Prosy Arceno • 4 年前 • 2102 次点击  

我如何检测哪些数据已更新,哪些数据已在数据库中创建 MyModel.objects.update_or_create() 方法

try:
    new_data = MyModel.objects.update_or_create(
        data_1 = active_sheet["{}{}".format("A", row)].value,
        data_2 = active_sheet["{}{}".format("B", row)].value,
    )  
    # default url
    url = reverse('admin:index') + 'some-url/'
    # if some users were only updated, not uploaded
        # pass the updated data to custom template 
        # return the current page with a table of the entries that were not added  
    self.message_user(request, 'Tagged Profile uploaded.')   
    # redirect to selected url
    return HttpResponseRedirect(url)
except Exception as e:
    messages.warning(request, '%s. If you are seing this, there is an error in your file.' % e)
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133035
文章 [ 2 ]  |  最新文章 4 年前
Prosy Arceno
Reply   •   1 楼
Prosy Arceno    5 年前

我让它与exists()一起工作。

try:
    if MyModel.objects.filter(
        name = active_sheet["{}{}".format("A", row)].value,
    ).exists():
        # add data to list 
    else: 
        # save the new user into the user model
        MyModel.objects.create(
            name = active_sheet["{}{}".format("A", row)].value,
        )
except Exception as e:
    messages.warning(request, '%s. If you are seing this, there is an error in your file.' % e)
furas
Reply   •   2 楼
furas    5 年前

基于文件 update_or_create 返回两个值 (object, created) 如果 created 是 True 然后是新的对象。

同样的方法也适用 get_or_create()