从表示父模型的表单编辑子模型的属性

时间:2013-07-29 12:21:31

标签: python django python-3.x django-admin

我有一个具有不同属性的人模型。一个人有一个Address,它是Person / parent模型的OneToOneField。当我在添加/编辑人员时使用管理员表单时,我还需要编辑地址属性,如line1,line2,mobile等。同样,我想从管理页面中删除一些人,它也应该删除匹配的引用,如地址。我已经尝试过很多东西,包括Inline和all。但是,我认为内联只有在地址与人有外键时才有效,反向是不可能的。任何形式的帮助都将受到高度赞赏......

class Person(models.Model):
    person_Id = models.CharField(max_length=32L, primary_key=True, db_column='PERSON_ID', editable=False)
    business_Address = models.OneToOneField(Address, unique=True, db_column='BUSINESS_ADDRESS_ID')

    class Meta:
        db_table = 'PD_PERSON' 

class Address(models.Model):
    # Field names made lowercase.
    address_id = models.IntegerField(primary_key=True, db_column='ADDRESS_ID')
    address_name = models.CharField(max_length=256L, db_column='NAME', blank=True)
    line1 = models.CharField(max_length=128L, db_column='LINE1', blank=True)
     class Meta:
        db_table = 'PD_ADDRESS' 

在admin.py~

class PersonInline(admin.TabularInline):
    model = Person

class PersonAdmin(admin.ModelAdmin):
    list_display = ('customer_Id', 'complete_Name', 'company')
    search_fields = ('name', 'customer_Id', 'email_Id')

class AddressAdmin(admin.ModelAdmin):
    inlines = [ PersonInline, ]

admin.site.register(Address, AddressAdmin)
#admin.site.register(Category)
#admin.site.register(Languages)
admin.site.register(Person, PersonAdmin)

1 个答案:

答案 0 :(得分:0)

问题1:删除人员删除时的地址

删除此人后,您可以使用post_delete信号自动删除地址。使用起来非常简单

from django.db.models.signals import post_delete
from web.programing.roxx.models import Person, Adress

@receiver(post_delete, sender=Person, dispatch_uid="person_post_delete")
def onPersonDelete(sender, instance, using, **kwargs):
    # be carefull, the instance doesn't exist anymore in the database
    adress_id = instance.business_Address.id
    if id != None:
        Adress.objects.filter(id=adress_id).delete()

但这不会在“你确定吗?”中显示地址。消息..


问题2:在人员管理页面中修改地址

目前,我没有看到任何解决方案比构建自定义表单以编辑Person模型更简单,并且覆盖add_view()和change_view()方法以使用O2O键初始化此表单..