Monday, August 29, 2016

A tricky query in one to many relationship - atleast for me:)

Hi,

I am looking for an elegant and efficient mechanism to have a query filter or a solution for the following one to many relationship model. Please note the following is just an illustration of the models - hope it should provide what I am looking for:

class A(models.Model):

name = models.CharField(_("Name"), max_length=255, unique=True)


class B(models.Model):
text = models.CharField(_("Text"), max_length=255, unique=True)
date_created = models.DateTimeField(_("Date Created"), auto_now_add=True) 
 a = models.ForeignKey(A, related_name='b')

To get all the instances of B associated with a specific instance of A (say 'a'), I could do the following : a.b.all()

The latest instance of B associated with 'a' would be : a.b.latest('date_created')

Now I would like to have a list of all instances of A where the latest instance of B associated with each instance of A will have the 'text' field as 'ABCD'. 

A.objects.filter(b__text='ABCD') will give all instances of A where each instance of A will have atleast one instance of B with 'text' = 'ABCD'.

There could be a brute force way of getting a solution for the above where in I can do A.objects.filter(b__text='ABCD')  and then go through each instance  of A in a for loop over the queryset and check for the latest instance of B for text='ABCD'.

As mentioned earlier, I am looking for an elegant and optimal way (if any in Django) for the above query.

Thanks.

 

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a9ea312a-578e-4a2f-a739-a38e87a4b15b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment