Thursday, January 29, 2015

Best way to get ForeignKey Related Objects?

I have two Models as shown below. Now when I have a specific AudioQuestionPair and I do something like

print pair.answers



it works just fine. However I can not do:

for answer in pair.answers



Using pair.answers.get.all() does also not work. So I have to do

answers
= Answer.objects.filter(audioQuestionPair=pair)



Isn't there a better way to design this? I can imagine that using objects.filter is more taxing on the database and uses more time than maybe another method?


class AudioQuestionPair(models.Model):
    audioData
= models.ForeignKey(AudioData)
    question
= models.ForeignKey(Question)
    database
= models.ForeignKey(Database)
    votes
= models.PositiveIntegerField(default=0)

   
class Meta:
        verbose_name
= "AudioData-Question Pair"
        verbose_name_plural
= "AudioData-Question Pairs"

   
def answers(self):
       
return Answer.objects.filter(audioQuestionPair=self.pk)

   
def __str__(self):
       
return "Database %s: AudioData %s - Question %s with %s Votes and Answers: %s" % (self.database, self.audioData, self.question, self.votes, self.answers())

"""
 Answer for a specific Audio-Question Pair
 cumulative
"""

class Answer(models.Model):
    body
= models.CharField(max_length=255)
    count
= models.PositiveIntegerField(default=0)
    isGroundtruth
= models.BooleanField(default=False)
    audioQuestionPair
= models.ForeignKey(AudioQuestionPair)

   
class Meta:
        verbose_name
= "Answer to AudioQuestionPair"
        verbose_name_plural
= "Answers to AudioQuestionPairs"

   
def __str__(self):
       
return "%s - %s times" % (self.body, self.count)



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/e8991d3a-1d32-4655-918f-26e0877898de%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment