简体   繁体   中英

How to manage many to one relationship in Django

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

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 automatically add new columns to the table when you add new fields to the model. 自动向表中添加新列。

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,
    ]

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