Hi,

I've done something similar to this using annotation. It is a bad
nasty, but should work.

Firstly annotate all the MyModel instances with the max value of the
pk of the MyOtherModel:

qs = MyModel.objects.annotate(last_pk=Max('myothermodel__pk'))

Then filter these based on the myString:

qs = qs.filter(myothermodel__myString=certainStringValue)

Now get a values list of the last_pks:

pks = qs.values_list('last_pk', flat=True)

Finally select all myOtherModel instances based on these pks:

other_models = myOtherModel.object.filter(pk__in=last_pks).

This will only do one SQL query.

This should be fine until you've got loads of potential hits, where
the sub-select will be a beast, although Postgres is certainly OK
accepting lists of 1000s of pks to filter on.

As an aside you might want to consider following the python style
guide (http://www.python.org/dev/peps/pep-0008/) to make your code a
bit more readable.

Euan


I think what you want is:

MyModel.objects.filter

On Jun 11, 1:27 pm, Odd <[email protected]> wrote:
> I have these two rather simple models that looks something like this:
>
> class MyModel(models.Model):
>       myName=models.CharField(max_length=60)
>
> class MyOtherModel(models.Model):
>        myString=models.CharField(max_length=60)
>        myModel=models.ForeignKey(MyModel)
>
> I will eventually have quite a number of MyOtherModelinstances. I have
> made a form where the users enters a string and a myModel instance,
> and it gets saved to the database. I need a query to get all the
> MyModel instances that has a certain stringvalue in myOtherModel, but
> only if it is the last entered one. My current solution is this:
>
> for i in mymodel.myothermodel_set.all():
>
> myOtherModel=MyOtherModel.objects.filter(myModel=i).order_by('-id')[:
> 1].get()
>          if myOtherModel.myString==certainStringValue:
>                objectsToRetur.append(i)
>
> This works, but I think it's not a very good. Is there maybe a better
> solution?
>
> Thanks!
>
> Odd-R.

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

Reply via email to