3

What would be the best solution for adding/editing multiple sub-types.

E.g a super-type class Contact with sub-type class Client and sub-type class Supplier. The way shown here works, but when you edit a Contact you get both inlines i.e. sub-type Client AND sub-type Supplier.

So even if you only want to add a Client you also get the fields for Supplier of vice versa. If you add a third sub-type , you get three sub-type field groups, while you actually only want one sub-type group, in the mentioned example: Client.

E.g.:

class Contact(models.Model):
    contact_name = models.CharField(max_length=128)

class Client(models.Model):
    contact = models.OneToOneField(Contact, primary_key=True)
    user_name = models.CharField(max_length=128)

class Supplier(models.Model):
    contact.OneToOneField(Contact, primary_key=True)
    company_name = models.CharField(max_length=128)

and in admin.py

class ClientInline(admin.StackedInline):
    model = Client

class SupplierInline(admin.StackedInline):
    model = Supplier

class ContactAdmin(admin.ModelAdmin):
    inlines = (ClientInline, SupplierInline,)

class ClientAdmin(admin.ModelAdmin):
    ...

class SupplierAdmin(admin.ModelAdmin):
    ...

Now when I want to add a Client, i.e. only a Client I edit Contact and I get the inlines for both Client and Supplier. And of course the same for Supplier.

Is there a way to avoid this? When I want to add/edit a Client that I only see the Inline for Client and when I want to add/edit a Supplier that I only see the Inline for Supplier, when adding/editing a Contact?

Or perhaps there is a different approach. Any help or suggestion will be greatly appreciated.

4

1 回答 1

1

如果不是使用一对一的外键来联系你,而是从它继承来的呢?

class Contact(models.Model):
    contact_name = models.CharField(max_length=128)

    class Meta:
        abstract=True # Don't use this line if you want Contact to have its own table

class Client(Contact):
    user_name = models.CharField(max_length=128)

class Supplier(Contact):
    company_name = models.CharField(max_length=128)

然后您可以注册客户和供应商,他们将共享联系人中的字段,但仍将彼此分开。

于 2010-03-15T03:49:17.843 回答