简体   繁体   中英

Traverse foreign key and pull remote model data into Django admin

Is is possible in the admin to pull a field from a remote model, if you have a local foreign key pointing to that model?

class FirstModel(models.Model):
    [...]
    value12 = models.CharField()

class SecondModel(models.Model):
    [...]
    firstmodel = models.ForeignKey(FirstModel)

And in the Admin I want to pull in value12, any time someone views/edits SecondModel. I figure I can do this through Inlines, but then I lose Fields and FieldSets ordering. Any other options? Ideal results would be sortable with fields/fieldsets, -and- read-only.

You should be able to access any field in the first model as: firstmodel__value12

For the list view for the SecondModel:

list_display = ('firstmodel__value12',)

For the edit view you can use formfield_overrides . To make it non-editable you specify a read-only widget, eg like this one or provide your own.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM