On 19/12/10 22:44, Andy wrote:


On Dec 19, 5:06 pm, "Jonas H."<jo...@lophus.org>  wrote:
On 12/19/2010 10:20 PM, Andy wrote:

Is there a way to specify JOIN using the Django ORM? The 2 tables I'm
joining aren't related through a foreign key.

Why don't you use a relation field in your models if your models are
related?

The tables are pre-existing.

I need to do something like:

SELECT * FROM TableA JOIN TableB ON TableA.id=TableB.some_id
WHERE TableA.id=1

Is that something that can be done through the ORM?


I think so, yes.  Something like this:

class ObjectA(models.Model):
  id = models.IntegerField(primary_key=True, db_column='id')

  class Meta:
    table_name = ('TableA')

class ObjectB(models.Model):
  id = models.IntegerField(primary_key=True, db_column='id')
  object_a = models.ForeignKey(ObjectA, db_column='some_id)

  class Meta:
    table_name = ('TableB')

You can then do something like

anObjectA = ObjectA.objects.filter(id=1)[0]
objectBs = ObjectB.objects.filter(object_a=anObjectA)

objectBs is all ObjectB instances that have an objectA with serial 1

You could do this instead to avoid the anObjectA instance:

objectBs = ObjectB.objects.filter(object_a__id=1)

Hope that helps.  I'm a bit confused by what you're selecting in:

> SELECT * FROM TableA JOIN TableB ON TableA.id=TableB.some_id
> WHERE TableA.id=1

What are you hoping to have returned?

Tim.

--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to