Django ManyToMany не извлекает связанные объекты
У меня есть следующая модель:
class Question:
text = models.TextField(_("Quiz"))
votes = models.ManyToManyField(
verbose_name=_("Votes"),
related_name="questions",
to="myapp.QuizVote",
blank=True,
)
def __str__(self):
return self.text
и еще один:
class QuizVote:
quiz = models.ForeignKey(
verbose_name=_("Quiz"), to="myapp.Question", on_delete=models.CASCADE
)
vote = models.ForeignKey(
verbose_name=_("QuizVote"),
to="myapp.Vote",
on_delete=models.CASCADE,
null=True,
blank=True,
)
def __str__(self):
return "{}".format(self.vote.name)
и последний
class Vote:
name = models.TextField(_("Vote"))
Когда я смотрю в Question администратора, в поле votes я ожидаю увидеть только те QuizVote записи, которые имеют тот же id, что и каждый конкретный Question. Однако каждый объект Question показывает все доступные записи в QuizVote без фильтрации на основе id.
Я пытался добавить этот метод в модель Question, но он не работает:
@receiver(m2m_changed, sender=Question.votes.through)
def retrieve_quiz_vote(sender, instance, action, **kwargs):
if action == "post_add":
instance._get_relavant_votes()
в модель Question добавлено следующее:
def _get_relavant_votes(self) -> None:
if isinstance(instance, Question) \
and hasattr(instance.__class__, 'objects'):
relevant_votes = instance.__class__.objects.filter(
votes__name__in=instance.votes.all()
).distinct()
return relevant_votes