Reputation: 113
I have the following code in my Django model:
from __future__ import annotations
from typing import Tuple, List, Dict, Callable
from datetime import date
from django.contrib.auth.models import User
from django.db.models import Model, ForeignKey, CASCADE, CharField, TextField, DateField
from enum import Enum
class RequestState(Enum):
OPEN = 'OPEN'
ACCEPTED = 'ACC'
DECLINED = 'DEC'
DELETED = 'DEL'
_state_parser: Dict[str, RequestState] = {
"OPEN": RequestState.OPEN,
"ACC": RequestState.ACCEPTED,
"DEC": RequestState.DECLINED,
"DEL": RequestState.DELETED
}
class ActionRequest(Model):
issuer = ForeignKey(User, on_delete=CASCADE, null=False, related_name="issuer")
receiver = ForeignKey(User, on_delete=CASCADE, null=False, related_name="receiver")
_state = CharField(max_length=4, default=RequestState.OPEN.value, null=False)
action = TextField(null=False)
issue_date = DateField(null=False, default=date.today)
last_change_date = DateField(null=False, default=date.today)
class InvalidRequestStateException(Exception):
def __init__(self, request: ActionRequest):
self.request = request
super(str(self))
def __str__(self):
return f'ActionRequest is in invalid state: {self.request.state}'
@property
def state(self) -> RequestState:
return _state_parser[self._state]
@state.setter
def state(self, state: RequestState) -> None:
self._state = state.value
and when i try creating a new model instance and saving it like this:
action_request = ActionRequest(
issuer=user,
receiver=receiver,
action=action
)
action_request.save()
i get the following error:
File ~\app\views\action_request_view.py", line 53, in post
action_request.save()
File "~\venv\lib\site-packages\django\db\models\base.py", line 678, in save
if field.is_relation and field.is_cached(self):
File "~\venv\lib\site-packages\django\db\models\fields\mixins.py", line 20, in is_cached
return self.get_cache_name() in instance._state.fields_cache
AttributeError: 'str' object has no attribute 'fields_cache'
I am using Django3.0. I Already tried using AcrionRequest.objects.create already, as well as changing the _state field to an IntegerField with the choices parameter but in that case i only get the same error but with 'int' instead of 'str'.
Upvotes: 2
Views: 631
Reputation: 88459
You have defined a field named _state
which is conflicting the _state
attribute of models.Model
class.
So change your _state
field to some other name.
ex:
class ActionRequest(Model):
# other fields
state = CharField(max_length=4, default=RequestState.OPEN.value, null=False)
Reference: Django : What is the role of ModelState?
Upvotes: 4