ValueError:以10为底的int()的无效文字似乎与ForeignKey有关 [英] ValueError: invalid literal for int() with base 10 seems to be related to ForeignKey

查看:65
本文介绍了ValueError:以10为底的int()的无效文字似乎与ForeignKey有关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试深入了解此错误。关于该主题的几个SO问题和答案包括:删除以前的迁移,在字段的模型中设置默认值或使用 GenericForeignKey 。到目前为止,没有人能解决我的问题。

Trying to get to the bottom of this error. Several SO questions on the subject and the answers range from: deleting previous migrations, setting default value in the model for the field, or using a GenericForeignKey. None have resolved my issue thus far.

我相当确定问题与 ForeignKey 有关,并已阅读即使字段为 CharField ,默认情况下仍使用 int()

I am fairly certain the issue is related to ForeignKey and have read it uses int() by default even if the field is CharField.

以下是我尝试使用的模型中的问题字段:

Here is the field in question in the model I am trying use:

product_code = models.ForeignKey(Products, null=False)

此处是其所引用的父模型中的字段(产品):

Here is the field in the parent model it is referring to (Products):

code = models.CharField(unique=True, max_length=16)

这是发生问题的查询:

# returns 'A_17'
product_code = Products.objects.get(id=data['product_id']).code

# error triggered here:
print(ProductPositions.objects.filter(product_code=product_code))

# ValueError: invalid literal for int() with base 10: 'A_17'

从头到尾都是字符串,但是我猜想 ForeignKey 默认为整数或与此有关的问题。不确定如何覆盖它,因为 default =''之类的方法不起作用。

So it appears to be string from end-to-end, but I guess with the ForeignKey "defaulting" to integer or something the issue is related to that. Not sure how to override that as something like default='' doesn't work.

不确定如何清除问题,感谢您的反馈。

Not sure how to clear up the issue so thanks for the feedback.

推荐答案

您正在使用实际的代码进行查找,并且正在期待首要的关键。您可以使用主键更改这两种方式

You are using the actually code to do the lookup and it is anticipating the primary key. You can alter this two ways Using the primary key:

product_code = Products.objects.get(id=data['product_id'])
print(ProductPositions.objects.filter(product_code=product_code.pk))

或使用代码( __ 将告诉Django通过外键引用该字段):

Or using the code (the __ will tell Django to refer the field through the foreign key):

product_code = Products.objects.get(id=data['product_id']).code
print(ProductPositions.objects.filter(product_code__code=product_code))

这篇关于ValueError:以10为底的int()的无效文字似乎与ForeignKey有关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆