Search code examples
djangonon-relational-database

How to join non-relational models in Django 1.3 on 2 fields


I've got 2 existing models that I need to join that are non-relational (no foreign keys). These were written by other developers are cannot be modified by me.

Here's a quick description of them:

Model Process

  • Field filename
  • Field path
  • Field somethingelse
  • Field bar

Model Service

  • Field filename
  • Field path
  • Field servicename
  • Field foo

I need to join all instances of these two models on the filename and path columns. I've got existing filters I have to apply to each of them before this join occurs.

Example:

A = Process.objects.filter(somethingelse=231)

B = Service.objects.filter(foo='abc')

result = A.filter(filename=B.filename,path=B.path)


Solution

  • This sucks, but your best bet is to iterate all models of one type, and issue queries to get your joined models for the other type.

    The other alternative is to run a raw SQL query to perform these joins, and retrieve the IDs for each model object, and then retrieve each joined pair based on that. More efficient at run time, but it will need to be manually maintained if your schema evolves.