Home > Net >  Model field dependent on same model foreign key object
Model field dependent on same model foreign key object

Time:08-09

Title seems complicated but its not really.

Lets say I have 2 models:

First is Choices that contains a title and boolean to see if the choice is correct or not.

class Choice(models.Model):
    content = models.CharField(max_length=200, default=None)
    correct = models.BooleanField(default=False)

Second is Check that checks if the use has chosen the correct choice:

class CheckQuestion(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    selected_choice = models.ForeignKey(Choice, on_delete=models.CASCADE)
    correct = models.BooleanField(default=None)

The correct field must be equal to the correct field of the selected choice. So basically:

correct = selected_choice.correct

I have tried implementing these using @property like this:

@property
    def correct(self):
        if self.selected_choice.correct:
            correct = True
        else:
            correct = False
        return correct

And I tried save like this:

def save(self,*args,**kwargs):
        self.correct = self.selected_choice.correct
        super(CheckQuestion,self).save(*args,**kwargs)

But neither worked, property method was giving giving a "cannot be null" error and save method just always returned false.

What else can I do?

CodePudding user response:

Firstly, you have set your default value on your BooleanField to None but you don't allow for null values. You should set this to False to make the main Choice model pattern. This would explain the method error.

correct = models.BooleanField(default=None) # change to False

Secondly, your model method can be made simpler - no if-statement needed.

@property
    def correct(self):
        return self.selected_choice.correct

As to why the save() override option always returns False, it would seem that the Choice object must have a False correct field. I would suggest triple checking whether that is the case or not - the save() code looks okay to me.

  • Related