Reputation: 292
I have a situation where object_id
for ForeignKey
accepts a PositiveIntegerField
but all id's
of my models are set as uuid
.
I looked up the documentation and found that i should use get_prep_value(value)
or get_db_prep_value(value, connection, prepared=False)¶
The question is how should i exactly do it?
Here is the code of model that contains the foreignRelation
target_ct = models.ForeignKey(ContentType,
blank=True,
null=True,
related_name='target_obj',
on_delete=models.CASCADE)
target_id = models.PositiveIntegerField(null=True,
blank=True,
db_index=True)
target = GenericForeignKey('target_ct', 'target_id')
created_at = models.DateTimeField(auto_now_add=True,
db_index=True)
Field from all other models
id = models.UUIDField(default=uuid4, primary_key=True, editable=False)
Whenever i try to save the model with the current setting i get this error
django.db.utils.DataError: integer out of range
Upvotes: 2
Views: 1155
Reputation: 476584
You make it a UUIDField
as well:
class MyModel(models.Model):
target_ct = models.ForeignKey(
ContentType,
blank=True,
null=True,
related_name='target_obj',
on_delete=models.CASCADE
)
target_id = models.UUIDField(
null=True,
blank=True,
db_index=True
)
target = GenericForeignKey('target_ct', 'target_id')
created_at = models.DateTimeField(auto_now_add=True, db_index=True)
Then you this can refer to all objects that have a UUIDField
as primary key.
Exactly this is however one of the reasons why it is often better to use an AutoField
as primary key: if all models have the same primary key you can refer to all objects with this. Now with this you can only refer to models with a UUIDField
as primary key.
Upvotes: 4