问题描述
我一直在寻找解决我问题的方法,但是我似乎无法弄清楚.
所以我有两个模型:
class消息(models.Model):_db ='somedb'id = models.IntegerField(primary_key = True)文字= models.TextField()MessageTags(models.Model)类:_db ='somedb'id = models.IntegerField(primary_key = True)文字= models.TextField()标签= models.ForeignKey(标签)消息=模型.ForeignKey(消息,related_name ='标签')
我可以使用以下调用查询给定消息的标签: test = Messages.get(id = 234124).tags.all()
^返回MessageTag的列表
我想做的是在理论上执行左联接,在该联接中,我使用关联的MessageTags对象获取特定条件下的所有消息.我被指示使用select_related的方向,但是我什么也无法工作.
如何获取消息列表,并将MessageTags作为每个.tags(或其他任何内容)的属性.
谢谢!
我不相信 select_related
将能够在您要的方法中执行.但是,实际上,左联接也不会.
这样想:一条消息可以有5个标签.如果进行联接,则结果集中该一条消息的5行,使其看起来像5条消息.
现在,正如您所指出的,您可以在单个消息上引用 .tags.all()
并获取与该消息关联的所有MessageTag.如果我正确理解您的情况,这实际上就是您要寻找的. p>
当然,如果您要优化执行的查询数,我建议您查看 prefetch_related
.这是如何使用此示例:
messages = Messages.objects.filter(text__icontains ='foobar').prefetch_related('tags')对于消息中的消息:对于message.tags.all()中的标签:print('消息ID',message.id,'-标签',tag.text)
应执行2个查询:
- 检索过滤的邮件列表
- 检索与这些消息相关的所有标签
I've been searching for a while now for a solution to my problem, but I can't seem to figure this out.
So I have two models:
class Messages(models.Model):
_db = 'somedb'
id = models.IntegerField(primary_key=True)
text = models.TextField()
class MessageTags(models.Model):
_db = 'somedb'
id = models.IntegerField(primary_key=True)
text = models.TextField()
tag = models.ForeignKey(Tag)
message = models.ForeignKey(Messages, related_name='tags')
I am able to query the tags for a given message using the following call:test = Messages.get(id=234124).tags.all()
^ returns a list of MessageTags
What I would like to do, is to in theory perform a left join, where I get all the messages for a certain criteria with the associated MessageTags objects. I was pointed in the direction of using select_related, but I cannot get anything to work.
How do I get the list of messages, with the MessageTags as an attribute of each as .tags (or anything else..)
Thank you!!
I don't believe select_related
is going to be able to perform in the method you're looking for. But really, neither would a left join.
Think of it this way: One message could have 5 tags. If you do a join, you will get 5 rows in your result set for that one message, which makes it look like 5 messages.
Now, as you noted, you can reference .tags.all()
on an individual message and get all of the MessageTags associated with that Message. If I understand your case correctly, this is actually what you're looking for.
Of course, if you're trying to optimize the number of queries executed, I would recommend looking at prefetch_related
. Here is an example of how you could use this:
messages = Messages.objects.filter(text__icontains='foobar').prefetch_related('tags')
for message in messages:
for tag in message.tags.all():
print('Message id', message.id, '- tag', tag.text)
That should execute 2 queries:
- Retrieve your filtered listed of messages
- Retrieve all tags related to those messages
这篇关于使用select_related获取related_name对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!