Django模型在调用object.update_or_create

时间:2019-02-28 21:32:14

标签: python mysql django python-3.x django-models

在以下模型上使用Django的update_or_create方法时遇到问题。我收到此错误:

  

ValueError:以10为底的int()无效文字:''

错误似乎总是抛出在update_or_create的最后一行,因为当我在语句中添加verified=False(默认值为False)时,该错误可以追溯到该行verified=False,而不是下面显示的行。

我的模特:

class Addresses(models.Model):
    customer = models.ForeignKey('Customers', on_delete=models.CASCADE)
    address_name = models.CharField(max_length=45)
    company = models.CharField(max_length=45)
    street1 = models.CharField(max_length=60)
    street2 = models.CharField(max_length=30, blank=True, null=True)
    street3 = models.CharField(max_length=30, blank=True, null=True)
    city = models.CharField(max_length=45)
    state = models.CharField(max_length=45)
    zip = models.IntegerField()
    country = models.CharField(default='US', max_length=45)
    phone = models.IntegerField(blank=True, null=True)
    residential = models.BooleanField(default=True)
    verified = models.BooleanField(default=False)

class Customers(models.Model):
    customer_name = models.CharField(max_length=75)
    email = models.CharField(max_length=60, blank=True, null=True)
    phone = models.IntegerField(blank=True, null=True)
    ss_customer_id = models.IntegerField(blank=True, null=True, unique=True)

功能:

def addAddress(self, address, customer_id):
    if address['name'] is not None and address['street1'] is not None and address['city'] is not None:
        if address['state'] is not None and address['postalCode'] is not None:

            address, created = Addresses.objects.update_or_create(
                address_name=address['name'],
                company=address['company'],
                street1=address['street1'],
                street2=address['street2'],
                street3=address['street3'],
                city=address['city'],
                state=address['state'],
                country=address['country'],
                phone=address['phone'],
                customer=customer_id #error thrown here
            )

            address.save()
            return address
    return False

数据:

address = {
    'name': 'Johnny Appleseed',
    'company': 'Apple Inc',
    'street1': '456 Street',
    'street2': 'APT 12',
    'street3': None,
    'city': 'City',
    'state': 'LA',
    'postalCode': '90000',
    'country': 'US',
    'phone': '4444444444',
}
customer_id = 2 #this is a valid primaryKey

self.addAddress(address, customer_id)

这是完整的追溯:

Traceback (most recent call last):
  File "/Users/jane/Code/dbmu-env/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Users/jane/Code/dbmu-env/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/jane/Code/dbmu-env/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/jane/Code/dbmu-env/env/lib/python3.7/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/jane/Code/dbmu-env/env/lib/python3.7/site-packages/django/utils/decorators.py", line 45, in _wrapper
    return bound_method(*args, **kwargs)
  File "/Users/jane/Code/dbmu-env/env/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/jane/Code/dbmu-env/env/lib/python3.7/site-packages/django/views/generic/base.py", line 88, in dispatch
    return handler(request, *args, **kwargs)
  File "/Users/jane/Code/dbmu-env/dbmu/webhooks.py", line 39, in post
    self.process_orders(orders)
  File "/Users/jane/Code/dbmu-env/dbmu/webhooks.py", line 57, in process_orders
    shipping = self.addAddress(order['shipTo'], customer_id)
  File "/Users/jane/Code/dbmu-env/dbmu/webhooks.py", line 88, in addAddress
    verified=False,
  File "/Users/jane/Code/dbmu-env/env/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Users/jane/Code/dbmu-env/env/lib/python3.7/site-packages/django/db/models/query.py", line 502, in update_or_create
    obj = self.select_for_update().get(**lookup)
  File "/Users/jane/Code/dbmu-env/env/lib/python3.7/site-packages/django/db/models/query.py", line 390, in get
    clone = self.filter(*args, **kwargs)
  File "/Users/jane/Code/dbmu-env/env/lib/python3.7/site-packages/django/db/models/query.py", line 844, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "/Users/jane/Code/dbmu-env/env/lib/python3.7/site-packages/django/db/models/query.py", line 862, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "/Users/jane/Code/dbmu-env/env/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1263, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "/Users/jane/Code/dbmu-env/env/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1287, in _add_q
    split_subq=split_subq,
  File "/Users/jane/Code/dbmu-env/env/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1225, in build_filter
    condition = self.build_lookup(lookups, col, value)
  File "/Users/jane/Code/dbmu-env/env/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1096, in build_lookup
    lookup = lookup_class(lhs, rhs)
  File "/Users/jane/Code/dbmu-env/env/lib/python3.7/site-packages/django/db/models/lookups.py", line 20, in __init__
    self.rhs = self.get_prep_lookup()
  File "/Users/jane/Code/dbmu-env/env/lib/python3.7/site-packages/django/db/models/lookups.py", line 70, in get_prep_lookup
    return self.lhs.output_field.get_prep_value(self.rhs)
  File "/Users/jane/Code/dbmu-env/env/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 1807, in get_prep_value
    return int(value)
ValueError: invalid literal for int() with base 10: ''

更新

我尝试了此操作,但仍然收到相同的错误:

def addAddress(self, address, customer_id):
    ...
    customer = Customers.objects.get(pk=customer_id)
    print(customer) #Customers object (2)

    address, created = Addresses.objects.update_or_create(
    ...

    customer=customer,
    )

我在做什么错?任何建议,将不胜感激:)

2 个答案:

答案 0 :(得分:1)

Address.customer是一个对象,而不仅仅是ID。为了填充它,您需要从数据库中检索它。因此:

 Customer.objects.get(customer_id)

希望有帮助。

答案 1 :(得分:0)

由于@ hd1,我得以弄清楚这一点。 Addresses.objects.update_or_create

有3处错误
  • 我传递的是客户主键而不是客户对象(hd1的答案)

  • 我没有为必填zip字段设置值

  • “电话号码”列的值超过了最大长度

由于某些原因,所有这些事情导致抛出了我的问题中的错误!

修复所有这些问题后,我不再出现错误。