[Answered ]-Django admin search and edit foreign fields

2👍

The + means just that – add a new instance of the related object and relate the object you’re editing to that. Because you’re adding a new object it will be blank to start. If you want to be able to edit existing related objects from another object’s admin you need to use inlines.

In your app’s admin.py have something like:

from django.contrib import admin
from yourapp.models import Address, Classified


class AddressInline(admin.TabularInline):
    model = Address


class ClassifiedAdmin(admin.ModelAdmin):
    inlines = [AddressInline,]


admin.site.register(Classified, ClassifiedAdmin)

Adding search from there is really easy.

...
class ClassifiedAdmin(admin.ModelAdmin):
    inlines = [AddressInline,]
    search_fields = [
        'field_you_want_to_search',
        'another_field',
        'address__field_on_relation',
    ]
...

Note the double underscore in that last one. That means you can search based on values in related objects’ fields.

EDIT: This answer is right in that your foreignkey relationship is the wrong way round to do it this way – with the models shown in your question Classified would be the inline and Address the primary model.

Leave a comment