Reputation: 159
I have a Django model 'Restaurant' which has a field parent_rest_id, which refers to one its parent restaurant which is saved in same table.
class Restaurant(DefaultColumns):
name = models.CharField(null=False, max_length=40)
restaurant_code = models.CharField(null=False, max_length=40, default='')
parent_rest_id = models.ForeignKey(
'self',
null=False,
db_column='parent_id',
default=0,
related_name='parent_id',
on_delete=models.CASCADE
)
restaurant_type = models.ForeignKey(
RestaurantType,
null=False, default='10',
db_column='restaurant_type',
related_name='restaurant_type',
on_delete=models.DO_NOTHING
)
Now when I try to create a row for it using Model.objects.create(**dict).
I get this error "TypeError: Direct assignment to the reverse side of a related set is prohibited. Use parent_id.set() instead."
I have made sure the parent_id is instance of Model Restaurant(Restaunt.objects.get(id=1))
Please let me know what I am doing wrong or I have created my model wrong, I am new to django.
PS: I don't have any customized serializer or model manager and DefaultColumns is parent class which inherits from model.Models
>>>Model.objects.create(**filtered_dict)
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.1\plugins\python-ce\helpers\pydev\_pydevd_bundle\pydevd_exec2.py", line 3, in Exec
exec(exp, global_vars, local_vars)
File "<input>", line 1, in <module>
File "C:\Users\Nerd\Documents\myvirtualenv\lib\site-packages\django\db\models\base.py", line 495, in __init__
_setattr(self, prop, kwargs[prop])
File "C:\Users\Nerd\Documents\myvirtualenv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 546, in __set__
% self._get_set_deprecation_msg_params(),
TypeError: Direct assignment to the reverse side of a related set is prohibited. Use parent_id.set() instead.
>>> filtered_dict
{'name': 'A2b', 'email': '', 'parent_id': <Restaurant: Default, >, 'restaurant_type': <RestaurantType: Store>, 'phone': '', 'address': '', 'city': '', 'postal_code': '', 'restaurant_code': 'A2B'}
>>>Model
<class 'Restaurant'>
Upvotes: 3
Views: 3253
Reputation: 159
I was able to resolve this error, since I have foreign key reference to the same table to which the key belongs to. So giving 'related name' was creating a backward relation with the model. Which was actually not needed. In Django if we give relate_name = '+', then Django will skip the creation of reverse relation. Hence this approach resolved my issue.
Upvotes: 2