首页 > 解决方案 > 无法在 Django 中创建对象

问题描述

我是 Django 新手,我正在努力根据我的应用程序中的模型创建和保存对象models.py

我正在使用的代码:

def search(request):
  try:
    if request.method == 'POST':
        product = request.POST.get('product')
        listed, not_listed = scrapeSellers(product)

        search = Searches(product=product,
                        no_of_sellers=len(listed),
                        valid_search=1,
                        best_price=listed[0]['cost'],
                        worst_price=listed[-1]['cost'])
        search.save()

        print(product)
        print(len(listed))
        print(listed[0]['cost'])
        print(listed[-1]['cost'])

    return render(request, 'app/search.html', {
        'listed' : listed,
        'not_listed' : not_listed,
    })

  except:
    return render(request, 'app/search.html', {})

我的models.py样子是这样的:

class Searches(models.Model):
   id = models.AutoField(primary_key=True)        
   product = models.CharField(max_length=8)           
   no_of_sellers = models.IntegerField()            
   valid_search = models.BooleanField()           
   best_price = models.FloatField(blank=True)
   worst_price = models.FloatField(blank=True)
   timestamp = models.DateTimeField(auto_now_add=True)

此外,我之后search.save()的打印语句没有执行,所以看起来对象创建失败,然后没有执行函数的其余部分。

我在控制台中没有收到任何错误消息,我的数据库中也没有发生任何事情。据我所见,我正在按照 Django Docs 示例中的说明进行操作:

p = Person(name="Fred Flintstone", shirt_size="L")
p.save()

我正在使用 MySQL 数据库、Python 3.6 和 Django 2.1.7。

对此的任何帮助将不胜感激!

标签: pythondjangodjango-models

解决方案


推荐阅读