Edited to use a one-to-one field
I'd like to add the area of a building to a django modeladmin. The table structure is
class Area(models.Model):
id= models.IntegerField('Buildings', db_column='id')
area=models.FloatField(blank=True, null=True)
class Buildings(models.Model):
id = models.AutoField(primary_key=True)
auto_sf = models.OneToOneField(Area, db_column='id')
I know that I can access the area attribute by using
b=buildings.get(id=1)
print(b.area.area)
But I don't understand how to incorporate b.area.area into the modeladmin - since this doesn't work.
class AdminSection(admin.ModelAdmin):
def area(self, obj):
return obj.area.area
fields=(('id','area'))
As stated, you are looking to use an inline model admin, like so:
class AreaInline(admin.StackedInline):
model = Area
class BuildingAdmin(admin.ModelAdmin):
inlines = (AreaInline, )
admin.site.register(Building, BuildingAdmin)
Also, your models should ideally have singular names, i.e. Building
, to make the more semantic sense - e.g. A building has an area. Unless the Buildings
object is literally managing multiple buildings per instance.