Reputation: 145
is there a way to get, from a list of ForeignKey-Parents, the one which got the newest Child? For example:
class parent(models.Model):
name = models.CharField(*)
class child(models.Model):
parent = models.ForeignKey(parent, *)
Now, given a list of parents, i want to get the parent, which had a child added last. Is there an easy way to do that in Django?
Thanks for the Answers!
Upvotes: 1
Views: 505
Reputation: 476574
You can not rely on the primary key to know what was last added. You better add a timestamp for this. So you might want to change your model to:
class Parent(models.Model):
name = models.CharField(max_length=128)
class child(models.Model):
parent = models.ForeignKey(Parent, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
Then you can obtain the parent with the most recent child with:
Parent.objects.filter(pk__in=list_of_parents).order_by('-child__created').first()
This will return a Parent
object if such parent exists, and None
otherwise.
If adding a timestamp is not an option, you can try to work with the primary key, but a database does not per se distributes primary key values in a certain order:
# does not per se works
Parent.objects.filter(pk__in=list_of_parents).order_by('-child__pk').first()
Upvotes: 2