views:

151

answers:

1

Hi,

I'm trying to integrate a legacy database in Django.

I'm running into problems with some weird tables that result from horribly bad database design, but I'm not free to change it.

The problem is that there are tables that dont have a primarykey ID, but a product ID and, here comes the problem, a lot of them are multiple in case of a certain column needs to have multiple values, for example

ID  |   ...   |  namestring

2   |   ...   |  name1
2   |   ...   |  name2

Is there a possibility to circumvent the usual primarykey behavior and write a function that returns an object for such an ID with multiple rows ? The column namestring could become a list then.

There is no manual editing required, as this is exported data from another system, I just have to access it..

Thanks for any hints !

+2  A: 

Django's ORM will have trouble working with this table unless you add a unique primary key column.

If you do add a primary key, then it would be trivial to write a method to query for a given product ID and return a list of the values corresponding to that product ID. Something like:

def names_for(product_id):
    return [row.namestring for row in ProductName.objects.filter(product_id=product_id)]

This function could also be a custom manager method, or a method on your Product model, or whatever makes most sense to you.

EDIT: Assuming you have a Product model that the product_id in this table refers to, and the only use you'll have for this table is to look up these names for a given product, your other option is to leave this table out of the ORM altogether, and just write a method on Product that uses raw SQL and cursor.execute to fetch the names for that product. This is nice and clean and doesn't require adding a unique PK to the table. The main thing you lose is the ability to administer this table via Django modelforms or the admin.

Carl Meyer
OK, thank you, that seems to be a reasonable solution. I would be happy though if there was a way to bypass the actual object access in some way via a manager or something like that ?
Homer J. Simpson