5

I am trying to make a many to one relationship and want to be able to control it (add -remove etc) via the admin panel. So this is my model.py:

from django.db import models

class Office(models.Model):
    name = models.CharField(max_length=30)


class Province(models.Model):
    numberPlate = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=20)
    office = models.ForeignKey(Office)

I want my model allow a province to have several Office.

So inside my admin.py:

class ProvinceCreator(admin.ModelAdmin):
        list_filter = ['numberPlate']
        list_display = ['name', 'numberPlate','office']

class OfficeCreator(admin.ModelAdmin):
        list_display = ['name']

This seems correct to me, however when I try to add a new province with the admin panel, I get this:

TemplateSyntaxError at /admin/haritaapp/province/

Caught an exception while rendering: no such column: haritaapp_province.office_id

Thanks

2 Answers2

6

It seams that you have your models setup backwards. If you want province to have many offices, then province should be a foreign key in the Office model.

from django.db import models

class Province(models.Model):
    numberPlate = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=20)

class Office(models.Model):
    name = models.CharField(max_length=30)
    province = models.ForeignKey(Province)

This would be straightforward and very intuitive way to implement one-to-many relationsship

As for the error that you are getting "no such column: haritaapp_province.office_id", when you add a new attribute (in your case office) to the model, you should either manually add column to the table. Or drop the table and re-run the syncdb:

 python manage.py syncdb

Django will not automatically add new columns to the table when you add new fields to the model.

Yuval Adam
  • 161,610
  • 92
  • 305
  • 395
Sergey Golovchenko
  • 18,203
  • 15
  • 55
  • 72
  • finally I could get it working, even " python manage.py syncdb" wouldn't enough so I had to delete the sqlite3 db and regen it :) One small question tho, foreign items show as Province_object while selecting/adding. How to fix it so it displays the name instead ? Regards –  Jul 28 '09 at 19:32
  • oh self edit: def __unicode__(self): return self.name did the job for me :p –  Jul 28 '09 at 19:41
  • in ref to "Django will not automatically add new columns" - Django-south does a good job of auto-managing model changes though I wish the migration naming scheme was more multi-dev friendly. – David Aug 30 '12 at 22:02
1

Have you looked at the docs for doing Inlines?

In your admin.py

class Office(admin.TabularInline):
    model = Office

class ProvinceAdmin(admin.ModelAdmin):
    inlines = [
        Office,
    ]
PhoebeB
  • 8,434
  • 8
  • 57
  • 76