Сложный кверисет с моделью типа контента django
У меня есть набор моделей, которые содержат контент, созданный и внесенный пользователями.
Модель Пользователь :
class User(models.Model):
first_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=150, blank=True)
is_active = models.BooleanField(default=True)
Модель Тип :
class Tip(models.Model):
title = models.CharField(max_length=30, blank=True)
content = models.CharField(max_length=150, blank=True)
Модель Пример:
class Example(models.Model):
headline = models.CharField(max_length=30, blank=True)
content = models.CharField(max_length=150, blank=True)
Модель Борьба :
class Struggle(models.Model):
headline = models.CharField(max_length=30, blank=True)
content = models.CharField(max_length=150, blank=True)
и модель UserContribution
class UserContribution(models.Model):
id = models.AutoField(primary_key=True)
contributed_by = models.ForeignKey(
settings.AUTH_USER_MODEL,
verbose_name="User that contributed the object",
on_delete=models.CASCADE
)
contributed_at = models.DateTimeField(auto_now_add=True)
object_id = models.PositiveIntegerField(
help_text="Primary key of the model",
)
content_type = models.ForeignKey(
ContentType,
on_delete=models.CASCADE
)
Я хочу иметь возможность выбрать набор пользователей и перечислить объекты вклада, которые они внесли (создали или обновили). Например,
[
{
"user_id": 1,
"first_name": "A",
"last_name": "B",
"tips": [
{
"id": 1,
"title": "abc",
"content": "bcd",
"contibuted_at": "2021-08-10"
},
{
"id": 2,
"title": "eabc",
"content": "abcd",
"contibuted_at": "2021-08-09"
}
],
"examples": [
{
"id": 1,
"headline": "abc",
"content": "bcd",
"contibuted_at": "2021-08-10"
},
{
"id": 2,
"headline": "eabc",
"content": "abcd",
"contibuted_at": "2021-08-09"
}
],
"struggles": [
{
"id": 1,
"headline": "abc",
"content": "bcd",
"contibuted_at": "2021-08-10"
},
{
"id": 2,
"headline": "eabc",
"content": "abcd",
"contibuted_at": "2021-08-02"
}
]
},
{
"user_id": 2,
"first_name": "C",
"last_name": "D",
"tips": [
{
"id": 1,
"title": "abc",
"content": "bcd",
"contibuted_at": "2021-09-09"
},
{
"id": 3,
"title": "eabc",
"content": "abcd",
"contibuted_at": "2021-09-02"
}
],
"examples": [
{
"id": 1,
"headline": "abc",
"content": "bcd",
"contibuted_at": "2021-09-10"
},
{
"id": 3,
"headline": "eabc",
"content": "abcd",
"contibuted_at": "2021-08-09"
}
],
"struggles": [
{
"id": 1,
"headline": "abc",
"content": "bcd",
"contibuted_at": "2021-09-10"
},
{
"id": 2,
"headline": "eabc",
"content": "abcd",
"contibuted_at": "2021-08-09"
}
]
}
]
Есть ли конкретный способ добиться этого, используя ORM Django, или я должен использовать необработанный SQL запрос? И какой способ был бы наиболее эффективным для достижения этого в необработанном SQL?