开发者

Inline multiple one-to-one fields in Django admin

I cannot get the admin module to inline two same field models in one-to-one relations. To illustrate it, I've made the following example, a model Person uses two addresses:

class Client(models.Model):
    # Official address
    official_addr = models.OneToOneField(Address, relat开发者_如何学Goed_name='official')
    # Temporary address
    temp_addr = models.OneToOneField(Address, related_name='temp')

I'd like to enable adding persons through Django admin interface with both addresses inlined. So far I have this code for admin configuration:

class ClientInline(admin.StackedInline):
    model = Client
    fk_name = "official_addr"

class ClientInline2(admin.StackedInline):
    model = Client
    fk_name = "temp_addr"

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

admin.site.register(Address, AddressAdmin)

It works perfectly for the first address, but with both addresses the interface is acting crazy - duplicating Client's fields instead of addresses. What I am doing wrong? It there a better way to have two same models inlined?


Replace your admin with the following:

class ClientInline(admin.StackedInline):
    model = Client
    max_num = 1

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

admin.site.register(Address, AddressAdmin)


I can't understand what you mean about 'acting crazy' by duplicating Client's fields. That's exactly what you've asked it to do - you have two inlines, both referring to Client. If this isn't what you want, you'll need to define it the other way round.


You can use ManyToMany relationship with through= In your example it will something about AddressType model

class Client(models.Model):
    addresses = ManyToManyField(Address, through=AddressType, related_name='address_clients')

class AddressType(models.Model):
    type = models.CharField('Type', max_length=255, unique=True)
    client = models.ForeignKey(Client, related_name='client_address_types')
    address = models.ForeignKey(Address, related_name='address_client_types')

Now add 2 objects by admin and use it

In future if you would like to add more types there are just need to add 1 type by admin)) for example working address

In view it easy to use:

client = Client.objects.get(id=...)
client_tmp_address = client.addresses.get(address_client_types_type='temporary') # If you added temporary Type before
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜