Search code examples
pythondjangodjango-modelslegacyinspectdb

Using joined results for Django model with legacy database schema


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?


Solution

  • 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.