0

Hi I have the following classes

Class Test1(models.Model):
    user = models.OneToOneField(User)
    myotherid = models.CharField(max_length=255)

Class TestData(models.Model):
    data = models.ForeignKey(Data)
    test1 = models.ForeignKey(Test1)

Class Data(models.Model):
    title = models.CharField(max_length=255)

I'm very new to Django models and all of this, how can I get all of Test1 items with myotherid=1234 and Data.title= "foo"

Essentially, doing this SQL:

select Test1.* from Test1 t, TestData td, Data d where t.myotherid=1234 and t.id = td.test1 and td.data = d.id and d.title = "foo"

Thanks for your help

KingFish
  • 8,773
  • 12
  • 53
  • 81
  • Just in case: please [do not use implicit `JOIN`'s notation](http://stackoverflow.com/a/44932/548696). – Tadeck Apr 22 '12 at 19:31

2 Answers2

0

The TestData class is superfluous, since it's just there to define a ManyToMany relationship, which you can do directly in Django by using a ManyToManyField - the intermediate class is still there, but not explicitly defined. You only need to define it if you need to store extra information on the relation itself.

So assuming you've added datas = ManyToManyField('Data') to your Test1 class, you can simply do this:

Test1.objects.filter(myotherid=1234, datas__title='foo')
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

I agree with Daniel that you might want to look into using ManyToManyField.

To answer your question though, here is what the Django code would look like with the model you provide:

Test1.objects.filter(myotherid=1234, testdata__data__title='foo')
Alex Marandon
  • 4,034
  • 2
  • 17
  • 21