I have a model like this:
class MyModel(models.Model):
status = models.CharField(choices=ChoicesModel.MY_CHOICES, max_length=128, blnk=True, null=True)
I have a separate model with the choices, for a matter of reusability. That works well so far.
Now, on the admin view, I need to show these choices, but in another model's list_display
. I have tried many things with no success.
These models are related with a ForeignKey
.
So, specifically, I need the parent model list_display
, to show the choice made on the child model related by the ForeignKey.
The ForeignKey
is defined on the child model, so it is related to the parent with this ForeignKey
field.
So, how can I read this choice made on the child object from the parent and show it on the list_display
of it's parent?
I'm using Django 1.11
EDIT
So far, I've tried with this:
related = models.OneToOneField('ChildModel', null=True, on_delete=models.SET_NULL)
Then, on admin:
def get_child_status(self, obj):
return obj.related.my_choice_field
get_child_status.short_description = 'Child status'
And, of course on my list_display:
list_display = ('field1', 'field2', 'get_child_status')
When I visit the changelist
view of the Parent model it throws me:
'NoneType' object has no attribute 'my_choice_field'
EDIT 2
This is the complete traceback:
Traceback (most recent call last):
File "C:\virtualenv\lib\site-packages\django\contrib\admin\utils.py", line 283, in lookup_field
f = _get_non_gfk_field(opts, name)
File "C:\virtualenv\lib\site-packages\django\contrib\admin\utils.py", line 317, in _get_non_gfk_field
field = opts.get_field(name)
File "C:\virtualenv\lib\site-packages\django\db\models\options.py", line 619, in get_field
raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name))
django.core.exceptions.FieldDoesNotExist: MyModel has no field named 'get_child_status'