Built-in multiple fields one-by-one in Django admin

I cannot get the admin module to embed two identical field models into a one-to-one relationship. To illustrate this, I made the following example: the Person model uses two addresses:

class Client(models.Model): # Official address official_addr = models.OneToOneField(Address, related_name='official') # Temporary address temp_addr = models.OneToOneField(Address, related_name='temp') 

I would like to enable adding people through the Django admin interface with both inlined addresses. So far I have this code for admin setup:

 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 fine for the first address, but with both addresses the interface is crazy - duplicating client fields instead of addresses. What am I doing wrong? Is this the best way to have two identical models?

+4
source share
3 answers

Replace the administrator as follows:

 class ClientInline(admin.StackedInline): model = Client max_num = 1 class AddressAdmin(admin.ModelAdmin): inlines = [ClientInline] admin.site.register(Address, AddressAdmin) 
+4
source

I can’t understand what you mean by β€œacting crazy,” duplicating client fields. This is exactly what you asked to do this - you have two built-in lines, both refer to the client. If this is not what you want, you need to define it the other way around.

0
source

You can use ManyToMany relationships with = In your example, it will be something like the 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 the future, if you want to add more types, you just need to add 1 type from the administrator)) for example, the work address

In mind that it is 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
source

All Articles