[英]Appending a 0 in front of a variable in Python
I have a variable called fab, and a Django queryset. 我有一个名为fab的变量和一个Django queryset。 As follows,
如下,
fab = self.request.GET.get('fab')
and my queryset, 和我的查询集
queryset_df = Table1.objects.filter(Q(fab=int(fab)) | Q(fab=int(0+fab))).values_list('masks').distinct()
As seen I want to append a zero in front of the fab in my Q, because sometimes the fab comes as a integer value and sometimes with a 0 infront. 可以看出,我想在Q中的fab前面附加一个零,因为有时fab是一个整数值,有时前面是0。 When I tried to add by
+
, it returned me an error like, unsupported operand type(s) for +: 'int' and 'unicode'
. 当我尝试用
+
进行加法时,它向我返回了类似+
的错误unsupported operand type(s) for +: 'int' and 'unicode'
。 Any idea why? 知道为什么吗? Thanks in advance.
提前致谢。
You should cast the 0 to unicode or string before concatenating. 串联前,应将0强制转换为unicode或string。
fab = "0" + fab
You can not concatenate a unicode variable with an integer, you can also not concatenate strings with integers or floats, so you need to convert one to the correct type. 您不能将unicode变量与整数连接,也不能将字符串与整数或浮点数连接,因此需要将其转换为正确的类型。
It sounds like your logic is wrong somewhere, 听起来您的逻辑在某处是错误的,
You are either trying to force an integer into a CharField
or you are trying to force a string into an IntegerField
. 您正在尝试将整数强制放入
CharField
或试图将字符串强制放入IntegerField
。 If its the former you're always going to struggle with having to cast values to get the correct results and if its the latter the leading 0 is pointless. 如果是前者,那么您将总是不得不转换值以获得正确的结果;如果是后者,则前导0毫无意义。
You should try to use the correct field type, it will even help with your model's validation. 您应该尝试使用正确的字段类型,它甚至可以帮助您进行模型的验证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.