Django with a single db raises "the current database router prevents this relation" when intializing model
In django I have the following database models:
ParentA
ParentB
Connector
which has a foreign key that references the modelParentA
and a foreign key that references the modelParentB
The Connector
model:
from django.db import models
class Connector(models.Model):
class Meta:
ordering = ["parent_a"]
unique_together = (("parent_a", "parent_b"),)
parent_a = models.ForeignKey(
ParentA,
on_delete=models.CASCADE,
related_name="connected_bs",
)
parent_b = models.ForeignKey(
ParentB,
on_delete=models.CASCADE,
related_name="connected_as",
)
In my code each time a ParentA
objects gets created I am finding which existing ParentB
objects can get connected with it and I am creating Connector
objects with the code that follows. The function that creates the Connector
objects is a method of the ParentA
, so self
here is a ParentA
object
from django.db import models
class ParentA(models.Model):
...
def create_connectors(self):
matching_p_b_objects = self.__get_matching_parent_b_objects()
new_matching_p_b_objects = matching_p_b_objects.filter(~Q(connected_as__parent_a=self))
Connector.objects.bulk_create(
[
Connector(parent_a=self, parent_b=parent_b)
for parent_b in new_matching_p_b_objects
]
)
The function is called all the time and it mostly works but some times it randomly throws the error
File "/code/backend/app/models/parent_a.py", line 989, in create_connectors
[
File "/code/backend/app/models/parent_a.py", line 990, in <listcomp>
Connector(parent_a=self, parent_b=parent_b)
File "/usr/local/lib/python3.10/site-packages/django/db/models/base.py", line 541, in __init__
_setattr(self, field.name, rel_obj)
File "/usr/local/lib/python3.10/site-packages/django/db/models/fields/related_descriptors.py", line 254, in __set__
raise ValueError(
ValueError: Cannot assign "<ParentA: 340459>": the current database router prevents this relation.
I am using a single postgres 17
database with python3.10
and django==4.0.3
Also, although it might be unrelated, in a different place in the code I get ValueError: save() prohibited to prevent data loss due to unsaved related object 'parent_a'.
although I am explicitly calling parent_a.save()
in a previous step.
Few months back, I faced a similar issue. Try passing the primary key (id) instead of the whole object when creating the Connector instances. That should hopefully solve the problem.