1

I'm using Django 1.6 to provide administrative functionality to a legacy database using Django's built-in admin feature.

I've used inspectdb to generate the models and cleaned them up appropriately, but there's one part that is bugging me. The schema is designed in an awkward way, such that I have a table customers:

class Customers(models.Model):
    id = models.IntegerField(primary_key=True)
    billing_id = models.IntegerField()
    option1 = models.BooleanField()
    created = models.DateTimeField()

as well as customer_data

class CustomerData(models.Model):
    cust_id = models.OneToOneField('Customers', primary_key=True)
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    phone = models.CharField(max_length=100)

The customer_data record always lines up 1-to-1 with the customers record, and there's too much legacy code to go back and change this. Is this some way I can have a single Django model that joins the records so that I can have a Customer object that has .first_name etc. attributes?

Tom
  • 681
  • 8
  • 14

1 Answers1

1

You said you're using Django's built-in admin features. If so, then you can create a ModelAdmin for Customers and then add CustomerData as an InlineModelAdmin. This will give you "the ability to edit models on the same page as a parent model."

In your case it would look something like:

from django.contrib import admin

class CustomerDataInline(admin.StackedInline):
    model = CustomerData

class CustomersAdmin(admin.ModelAdmin):
    inlines = [CustomerDataInline,]

admin.site.register(Customers, CustomersAdmin)

This will allow you to edit the related fields first_name, last_name, and phone in the form of each Customers.

pcoronel
  • 3,833
  • 22
  • 25
  • Thanks for your answer. Is there any way to represent those two tables in the same model? In some cases we won't be using Django's Admin and may need to search based on customer attributes, and it would simplify the controller logic immensely to be able to filter a single model by fields on both of those tables. – Tom Jun 04 '14 at 15:08