形成一对多关系的Django查询集

时间:2021-12-22 20:24:45

I have a Django model defining a photo:

我有一个定义照片的Django模型:

class Pic(models.Model):
    image = models.ImageField(upload_to=upload_pic_to_location, storage=OverwriteStorage())
    owner = models.ForeignKey(User)
    upload_time = models.DateTimeField(db_index=True, auto_now_add=True)

And another defining a message the above photo can be sent as:

另一个定义上述照片的消息可以发送为:

class PicMessage(models.Model):
    which_pic = models.ForeignKey(Pic)
    sending_time = models.DateTimeField(auto_now_add=True)

I.e. same pic can be sent as a different message multiple times. What's the most efficient way to find the most recent PicMessage sent by a given user?

即相同的pic可以多次作为不同的消息发送。找到给定用户发送的最新PicMessage的最有效方法是什么?


I'm trying this: PicMessage.objects.filter(which_pic__in=Pic.objects.filter(owner=self.request.user)).latest('sending_time')

我正在尝试这个:PicMessage.objects.filter(which_pic__in = Pic.objects.filter(owner = self.request.user))。latest('sending_time')

1 个解决方案

#1


0  

PicMessage.objects.filter(which_pic__owner=user).order_by('-sending_time').first()

#1


0  

PicMessage.objects.filter(which_pic__owner=user).order_by('-sending_time').first()