Django获得自定义m2m字段值

时间:2017-05-16 01:53:50

标签: python django manytomanyfield

情景:

我在测试库中有很多问题,其中一些是类似的。所以我定义了一个自定义m2m字段,让我知道每两个问题的相似性。

我的模特:

class Question(models.Model):
    number = models.SmallIntegerField()
    question = models.TextField()
    related_q = models.ManyToManyField("self", related_name='RelatedQuestion', 
                                       through='RelatedQuestion',
                                       symmetrical=False,
                                       blank=True)


class RelatedQuestion(models.Model):
    from_question_id = models.ForeignKey(Question, on_delete=models.CASCADE, blank=True, related_name="source+")
    to_question_id = models.ForeignKey(Question, on_delete=models.CASCADE, blank=True, related_name="destiny+")
    similarity = models.FloatField()

相似性如下所示。 enter image description here

问题

我如何在以后获得相似性?

>>> Question.objects.get(pk=5757).related_q.first()
<Question: 100-1-1-1  下顎骨中最重要的力軌(trajectory)為何? >

>>> Question.objects.get(pk=5757).related_q.first().id
1

>>> Question.objects.get(pk=5757).related_q.similarity
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'ManyRelatedManager' object has no attribute 'similarity'

>>> Question.objects.get(pk=5757).related_q.first().similarity
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'Question' object has no attribute 'similarity'

>>> Question.objects.get(pk=5757).RelatedQuestion_set.all()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'Question' object has no attribute 'RelatedQuestion_set'

>>> Question.objects.get(pk=5757).RelatedQuestion.similarity
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'ManyRelatedManager' object has no attribute 'similarity'

1 个答案:

答案 0 :(得分:1)

similarity字段位于RelatedQuestion,而您正试图在Question上访问该字段。你也无法通过该领域获得它,因为可能有许多相关的问题;它会选择哪一个返回相似度值?

此外,您无法访问&#34;通过&#34;通过经理建立模型,这就是您在ManyRelatedManager上收到错误的原因。

您可以通过_set反向查找来访问直通模型。

Question.objects.get(pk=5757).source_set.first().similarity

注意:在我写这篇文章的时候,我无法测试上面的代码,所以请注意它,因为它指向正确的方向。