In my DRF project, I use multiple databases to handle the data I don't specify a default database in settings.
whenever I use the model serializer with ForeignKey relation Django emits the following error
settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.
I know why this error is prone because by default ModelSerilizer sets the field of an FK relation like this
serializers.PrimaryKeyRelatedField(
queryset=ItemCategory.objects.all(),
required=True, allow_null=False)
because I don't have a default DB it will show that error it's fine
to overcome I did something like this
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = ('id', 'name', 'category')
def __init__(self, instance=None, data=..., **kwargs):
user = kwargs.get('context').get('user')
database = user.db
self.fields['category'] = serializers.PrimaryKeyRelatedField(
allow_null=True, queryset=ItemCategory.objects.using(database).all(), required=False)
super().__init__(instance, data, **kwargs)
but when I print the field category it returns something like this
PrimaryKeyRelatedField(allow_null=True, queryset=<QuerySet [<ItemCategory: ItemCategory object (1)>]>, required=False)
instead of the query param, it assigns the querySet
is there any solution for this (I am not sure assigning the fields manually from init method works fine)