如何解决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()
获得的新项目更新数据库中的现有记录
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。