以 10 为底的 int() 的 Django 通用外键无效文字
Django Generic Foreign Key invalid literal for int() with base 10
我有一个使用通用外键的模型
class Flag(TimeStampedModel):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
然而,当我尝试保存外键为 base64 编码的新标志时,出现错误:
ValueError: invalid literal for int() with base 10: '7_p1seHP7FR0KxN9+hHaCaNg'
看来Generic Foreign Key只能是int!我该如何解决这个问题,因为并非我所有的键都是整数。
我是如何得到错误的:
u = User.objects.get(pk="7_p1seHP7FR0KxN9+hHaCaNg")
Flag.objects.create(content_object=u)
here 它说通用外键可以是一个字符:
...For example, if you want to allow generic relations to models with
either IntegerField or CharField primary key fields, you can use
CharField for the “object_id” field on your model since integers can
be coerced to strings by get_db_prep_value()...
可以是原始主键可以cast/coerced的任何东西。您也可以使用 TextField,但要牺牲性能。
我有一个使用通用外键的模型
class Flag(TimeStampedModel):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
然而,当我尝试保存外键为 base64 编码的新标志时,出现错误:
ValueError: invalid literal for int() with base 10: '7_p1seHP7FR0KxN9+hHaCaNg'
看来Generic Foreign Key只能是int!我该如何解决这个问题,因为并非我所有的键都是整数。
我是如何得到错误的:
u = User.objects.get(pk="7_p1seHP7FR0KxN9+hHaCaNg") Flag.objects.create(content_object=u)
here 它说通用外键可以是一个字符:
...For example, if you want to allow generic relations to models with either IntegerField or CharField primary key fields, you can use CharField for the “object_id” field on your model since integers can be coerced to strings by get_db_prep_value()...
可以是原始主键可以cast/coerced的任何东西。您也可以使用 TextField,但要牺牲性能。