0

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'
NeoVe
  • 3,857
  • 8
  • 54
  • 134
  • 1
    Possible duplicate of [Can "list\_display" in a Django ModelAdmin display attributes of ForeignKey fields?](https://stackoverflow.com/questions/163823/can-list-display-in-a-django-modeladmin-display-attributes-of-foreignkey-field) – Mikhail Burshteyn Mar 18 '19 at 14:26
  • But I'm trying those solutions, it always says that the parent class doesn't have attribute (the onetoone field) which is non sense – NeoVe Mar 18 '19 at 14:43
  • 1
    Please update the question with some code and the traceback of the error that you are getting – Mikhail Burshteyn Mar 18 '19 at 15:06
  • Done, can you have a look? Thank You very much – NeoVe Mar 18 '19 at 15:12
  • Added the complete traceback, sorry – NeoVe Mar 18 '19 at 15:15
  • 1
    Your `get_child_status` assumes that `obj.related` always exists, which seems to be not the case. You need to add an existence check. – Mikhail Burshteyn Mar 19 '19 at 13:28

0 Answers0