Django.db.utils.OperationalError: sub-select возвращает 8 колонок - ожидалось 1

Я пытаюсь создать QuerySet, который собирает все теги, размещенные во всех вопросах данного пользователя. Кроме того, аннотируйте каждый экземпляр Tag, чтобы узнать, сколько раз каждый тег был опубликован.

Однако проблема, с которой я столкнулся, заключается в следующей ошибке, которая возникает:

  • django.db.utils.OperationalError: sub-select returns 8 columns - expected 1

На что ссылается эта ошибка и как ее можно устранить, чтобы получить вышеупомянутый желаемый QuerySet?

class TestProfileInstanceTagData(TestCase):

    @classmethod
    def setUpTestData(cls):
        cls.user = get_user_model().objects.create_user("ItsMe")
        profile = Profile.objects.create(user=cls.user)

        tag1 = Tag.objects.create(name="TagA")
        tag2 = Tag.objects.create(name="TagB")
        tag3 = Tag.objects.create(name="TagZ")

        question1 = Question.objects.create(
            title="This is a title about question1",
            body="This is the post content about question1",
            profile=profile
        )
        question1.tags.add(tag3)

        question2 = Question.objects.create(
            title="This is a title about question2",
            body="This is the post content about question2",
            profile=profile
        )
        question2.tags.add(*[tag1, tag3])

        question3 = Question.objects.create(
            title="This is a title about question3",
            body="This is the post content about question3",
            profile=profile
        )
        question3.tags.add(tag2)

        cls.queryset = profile.get_tag_post_data()

    def test_user_posted_tag_queryset(self):
        self.assertEqual(self.queryset.count(), 3)
class Profile(Model):
    user = OneToOneField(settings.AUTH_USER_MODEL, on_delete=CASCADE)

    def get_tag_post_data(self):
        questions_with_tag = self.questions.filter(tags__name=OuterRef("name"))
        return Tag.objects.filter(
            question__profile=self
        ).distinct().annotate(count=Count(Subquery(questions_with_tag)))
class Tag(Model):

    name = CharField(unique=True, max_length=25)


class Post(Model):

    body = TextField()
    date = DateField(default=date.today)
    comment = ForeignKey('Comment', on_delete=CASCADE, null=True)
    profile = ForeignKey(
        'authors.Profile', on_delete=SET_NULL, null=True,
        related_name='%(class)ss',
        related_query_name="%(class)s"
    )
    vote = GenericRelation(
        'Vote', related_query_name="%(class)s"
    )
    score = IntegerField(default=0)


class Question(Post):

    title = CharField(
        max_length=80, unique_for_date="date",
        help_text="Concisely state the problem you're having",
        error_messages={
            "max_length": "The title of your question is too long"
        }
    )
    tags = ManyToManyField(
        'Tag', related_name="questions", related_query_name="question"
    )
    views = IntegerField(default=0)
Вернуться на верх