【问题标题】:Error 'expected string or bytes-like object' in DjangoDjango中的错误“预期的字符串或类似字节的对象”
【发布时间】:2020-11-19 19:23:43
【问题描述】:

我正在尝试在我的 Django 模型中创建新记录,但我做不到。这是 Sell 类模型:

class Sell(models.Model):
    item = models.OneToOneField(Buy, related_name='sell', on_delete=models.CASCADE)
    date = models.DateField(default=timezone.now)
    discount = models.DecimalField(max_digits=6, decimal_places=2)
    total_paid = models.DecimalField(max_digits=6, decimal_places=2)
    buyer = models.ForeignKey(User, related_name='sell', on_delete=models.CASCADE)

这是我view.py中的代码:

    Sell.objects.create(item=item,
                        date=timezone.now,
                        discount=Decimal(0.00),
                        total_paid=cart.get_total_price(),
                        buyer=request.user, )

如果我打印所有这些变量,结果是:

    print(item)
    266
    print(type(item))
    <class 'dma.models.Buy'>
    
    print(timezone.now)
    <function datetime.date at 0x03D3F460>
    print(type(timezone.now))
    <class 'function'>
    
    print(type(Decimal(0.00)))
    <class 'decimal.Decimal'>
    
    print(cart.get_total_price())
    68.00
    print(type(cart.get_total_price()))
    <class 'decimal.Decimal'>
    
    print(request.user)
    Felipe
    print(type(request.user))
    <class 'django.utils.functional.SimpleLazyObject'>

错误:

异常类型:TypeError 异常值:
预期的字符串或类似字节的对象

【问题讨论】:

  • 您图片中的代码与您的问题中的代码不同。
  • @AKX 他刚刚重新排序它是一样的,就像他把它放在 SO 上的打印语句之前的 create 函数一样,但在他的代码中它排在最后。
  • @RaoufM 不,不是。回溯显示date=datetime.date,粘贴的代码没有。
  • 各位,谢谢!该代码现在正在运行。我应该弄错了,初始代码:Sell.objects.create(item=item, date=timezone.now(), discount=Decimal(0.00), total_paid=cart.get_total_price(), buyer=request.user , ) 现在运行正常。

标签: python django


【解决方案1】:

您应该通过调用函数评估 timezone.now,

date=timezone.now<b>()</b>
Sell.objects.create(item=item,
              date=timezone.now(),
              discount=Decimal(0.00),
              total_paid=cart.get_total_price(),
              buyer=request.user, )

【讨论】:

  • 非常感谢!我不知道到底发生了什么,但代码现在可以正常工作,没有这个 'timezone.now' 评估。顺便说一句,为什么这个评估是必要的?
  • timezone.now 是函数,timezone.now() 是函数的结果
  • 在这种情况下,我没有进行评估,并且代码似乎仅使用以下几行即可正常工作: Sell.objects.create(item=item, date=timezone.now(), discount=Decimal( 0.00),total_paid=cart.get_total_price(),buyer=request.user,)。如果我不添加第一行 'date=timezone.now()' 是否一切正常?
猜你喜欢
  • 2017-01-19
  • 1970-01-01
  • 1970-01-01
  • 2020-11-09
  • 2017-03-14
  • 1970-01-01
  • 2020-07-08
  • 2020-08-24
  • 1970-01-01
相关资源
最近更新 更多