简体   繁体   English

有没有办法在DRF中获取所有ManyToMany相关对象

[英]Is there a way to get all ManyToMany related objects in DRF

I have Tags in my application and it's possible to Tag different things like News, Events... News and Events have a ManyToMany relation to Tags. 我的应用程序中有标签,并且可以标记不同的东西,例如新闻,事件...新闻和事件与标签具有ManyToMany关系。 Is it possible to get every object where the Tag is used? 是否可以获得使用标签的每个对象?

My Models (shortened) look like this: 我的模型(简称)如下所示:

Tag Model 标签模型

class Tag(models.Model):
    title = models.CharField(max_length=35)

News Model 新闻模型

class News(models.Model):
    title = models.CharField(max_length=75)
    tag = models.ManyToManyField(Tag, related_name="news")

Event Model 事件模型

class Event(models.Model):
    title = models.CharField(max_length=75)
    tag = models.ManyToManyField(Tag, related_name="event")

I know that I can get all News that have the Tags assigned by 我知道我可以获取所有具有由分配标签的新闻

tag = self.get_object()
tag.news.all()

But is it possible to get all News, Events... without 10 requests? 但是有可能在没有10个请求的情况下获取所有新闻,事件吗? I'm looking for something like tag.all.all() 我正在寻找类似tag.all.all()东西

try this 尝试这个

tag.news.all() | tag.event.all()

"news" and "event" are accessible due to reverse relationship here which are defined in their respective model fields with the keyword "related_name". 由于这里存在反向关系,因此可以访问“新闻”和“事件”,它们在各自的模型字段中使用关键字“ related_name”定义。

note that this may give duplicate tags as it is a union between the two. 请注意,这可能会产生重复的标签,因为这是两者之间的联合。 for distinct tags, 对于不同的标签,

(tag.news.all() | tag.event.all()).distinct()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM