[英]Django: Filter queryset by property of Element
I have two models, Chat and DeletedChat.我有两个模型,Chat 和 DeletedChat。 Now i want to get all chats of a
user
, removing those which from_date
-fields, in DeletedChat
, are bigger then the last_updated
ones of the chat itself.现在我想获取
user
所有聊天记录,删除那些from_date
字段,在DeletedChat
,比聊天本身的last_updated
大的那些。 How do i do that?我怎么做?
class Chat(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
last_updated = models.DateTimeField(auto_now=True)
class DeletedChat(models.Model):
chat = models.ForeignKey(Chat, on_delete=models.CASCADE)
from_date = models.DateTimeField(default=timezone.now)
And in my views.py
I tried:在我的
views.py
我尝试了:
chat_ids = request.user.deletedchat_set.exclude(from_date__lt='chat__last_updated').values_list('chat', flat=True)
which gives me the following error: ['“chat__message__set__last” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']
这给了我以下错误:
['“chat__message__set__last” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']
['“chat__message__set__last” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']
Thanks for your Help!感谢您的帮助!
You can work with an F
object to refer to a field:您可以使用
F
对象来引用字段:
from django.db.models import F, Q
Chat.objects.filter(Q(deletedchat=None) | Q(deletedchat__form_date__lt=F('last_updated')))
This will return Chat
objects for which there is no related DeletedChat
object, or where the DeletedChat
object has a form_date
that is less than the last_updated
field of the Chat
object.这将返回没有相关
DeletedChat
对象的Chat
对象,或者DeletedChat
对象的form_date
小于Chat
对象的last_updated
字段。
We can also make use of .exclude()
:我们也可以使用
.exclude()
:
from django.db.models import F
Chat.objects.exclude(
deletedchat__form_date__gte=F('last_updated'))
The two are however not equivalent if there are multiple related DeleteChat
objects.但是,如果有多个相关的
DeleteChat
对象,则两者并不等效。 In that case the .filter(..)
variant can still contain a Chat
if there exists at least one related DeleteChat
object for which the from_date
is less than the last_updated
field.在这种情况下,如果存在至少一个相关的
DeleteChat
对象且from_date
小于last_updated
字段,则.filter(..)
变体仍然可以包含Chat
。 For the .exclude()
, it will exclude it from the moment one of the from_date
s is greater than the last_updated
field.对于
.exclude()
,它将从from_date
之一大于last_updated
字段的那一刻起排除它。
In case a Chat
object has at most one DeletedChat
object, you might want to conider a OneToOneField
[Django-doc] instead.如果
Chat
对象至多有一个DeletedChat
对象,您可能需要考虑使用OneToOneField
[Django-doc] 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.