Home > Software engineering >  Django model filter objects having a field as self object(please read body of question)
Django model filter objects having a field as self object(please read body of question)

Time:07-13

I have two models Quiz and ABCD ABCD is connected to Quiz using oneToOneField Quiz model will be used to store a quiz and ABCD is a model used to store result for a user one Quiz will be connected to Multiple ABCD(one quiz will have multiple results) inside Quiz model i want a method which will return all results for that quiz(ABCD objects having That quiz as its quiz field) what should i write to filter the ABCD with that Quiz

class Quiz(models.Model):
    name=models.CharField(max_length=250)
    def show_results(self):
        return ABCD.objects.filter(quiz=what to write here)

class ABCD(models.Model):
    quiz=models.OneToOneField(Quiz,on_delete=models.CASCADE)
    points=models.IntegerField()

CodePudding user response:

You don't need to use a model filter to get the ABCDs connected to Quiz, Django creates a related_name automatically (you can specify one on the field if you prefer a different name). You can access it by:

def show_results(self):
   return self.abcd_set.all()

You wouldn't really need a 'show_result' method with this, but that's up to you.

On a related note, your model relations are one-to-one when I believe you want to use a many-to-one or models.ForeignKey field. The one-to-one accessor would just be quiz.abcd because there's only one!

CodePudding user response:

If one Quiz will have multiply ABCD you should change OneToOneField to ForeignKey:

class ABCD(models.Model):
    quiz=models.ForeignKey(Quiz,on_delete=models.CASCADE)
    points=models.IntegerField()

then with instance of Quiz model:

quiz = Quiz.objects.get(pk=1) // for example

to get queryset of all ABCD objects that have this quiz as foreignkey:

quiz.abcd_set.all()
  • Related