3

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 Buildings(models.Model):
    id = models.AutoField(primary_key=True)
    auto_sf = models.OneToOneField(Area, db_column='id')

class Area(models.Model):
    id= models.IntegerField('Buildings', db_column='id')
    area=models.FloatField(blank=True, null=True) 

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'))
user2872147
  • 169
  • 1
  • 2
  • 11
  • 2
    What exactly are you trying to do? If you want to be able to set the `area` from the `Building` admin, look into using [inlines](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.InlineModelAdmin). If you just want to display the `area` on the change list page, use [`list_display`](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display). Incidentally, if this is really a one-to-one relationship you might be better off using a `OneToOneField` rather than a `ForeignKey`. – Kevin Christopher Henry Mar 05 '14 at 21:21
  • I've edited the question to use a one to one field. I would prefer to keep it all in the same admin, rather than using an inline, if possible, since the inline would require moving the fields around on the screen. – user2872147 Mar 05 '14 at 21:28
  • 2
    Shouldn't `Area` inherit from `models.Model`? –  Mar 05 '14 at 22:56
  • sorry, yes, I simplified the code for this example, and you are correct. – user2872147 Mar 06 '14 at 01:36
  • Ultimately, what I did was add the readonly attribute that was missing. readonly_fields = ('area') – user2872147 Jun 09 '15 at 17:42

1 Answers1

4

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.