简体   繁体   中英

Link child objects to parent objects in parent's admin view in Django

I have two classes: Sensor and Apartment. Sensor class has foreign key for Apartment so you can assign sensors to apartments. Everything works great, but I can't find I simple way to assign existing sensors to apartments in the apartment view. I created simple inline editor for the sensor which allows creation of new sensors, but how should I add option to link existing sensors from other apartments for example in the same view?

class SensorInline(admin.TabularInline):
    model = Sensor
    extra = 1

class ApartmentAdmin(admin.ModelAdmin):
    inlines = [SensorInline]

admin.site.register(Apartment, ApartmentAdmin)

Maybe easier to create a sensor admin, and do it that way.

Class SensorAdmin(admin.modelAdmin):
    model=Sensor 

admin.site.register(Sensor, SensorAdmin)

That should give you a page with a list of sensors in your admin. Click one, and you should have an edit page for that sensor. Provided your foreign keys are set up correctly in the model file, you should have a drop down with the apartments to choose from.

(Your current setup should work as well, but may be less intuitive to use).

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