Django不会更新我的模型对象,而是创建了新的

问题描述

所以这是我的简单功能,可以正常工作。基本上是从该站点提取数据。

def mega():
    pageNumber = 1
    nextPage = True
    proList = []
    while nextPage:
        url = "http://www.mega.pk/mobiles/{}/".format(pageNumber)
        response = get(url)
        soup = BeautifulSoup(response.text,features="lxml")
        ul = soup.find('ul',class_='item_grid list-inline clearfix')
        li = ul.find_all('li',class_='col-xs-6')
        if not li:
            break
        for link in li:
            if link.find("div",class_="was"):
                title = link.find(id="lap_name_div").text.replace("\n","")
                data = link.find("div",class_="cat_price").text.replace(
                    "\n","").replace("\t","").replace(" ","")
                lists = data.split("-")
                if len(lists) > 2:
                    price = lists[1].replace("PKR","") + "-PKR"
                else:
                    price = data
                price = int(price.replace(",","").replace(
                    '-',"").replace("PKR",""))
                productUrl = link.find("a")['href']
                image = link.find("img")['data-original']
                pro = Product(title=title,price=price,productUrl=productUrl,imageUrl=image,site="mega.pk")
                proList.append(pro)    
        pageNumber = pageNumber + 1
    return proList

但是下面是我的观点,当我尝试分配item.price = product.price时。然后不进行更新而是创建新实例。

def scraper(request):
    products = mega()
    proList = Product.objects.all()
    for product in products:
        for item in proList:
            if product.title == item.title and product.price == item.price:
                break
            elif product.title == item.title and product.price != item.price:
                notify = Notification(user = request.user,changeMessage="Price updated")
                notify.save()
                item.price = product.price
                break

    return redirect("home")

赞这个 enter image description here

解决方法

由于您使用proList = Product.objects.all()从数据库中获取了项目,然后使用for product in products:对其进行了遍历

您应将其从item.price = product.price更改为:

product.price = item.price
product.save() 

然后,您将使用从mega()获得的新项目更新数据库中的现有记录

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...