Django - size of ArrayField based on a field value of a related model

199 Views Asked by At

I have 2 models: Report and STO with a one-to-many relationship between them, so a STO can have many related reports.

STO model

class STO(TerminableWithTerminableRelatedModel):
    name = models.CharField(_('name'), unique=True, blank=False, max_length=255)
    description = models.TextField(_('description'), blank=True, null=True)
    answer_no = models.PositiveSmallIntegerField(_('number of answers'), default=5) # that's the value I'm interested in
    result_note = models.TextField(_('STO result note'), blank=True, null=True)

Report model

class Report(models.Model):

    @property
    def answer_no(self):
        return STO.objects.get(id=self.STO).answer_no

    date = models.DateField(_('date'), blank=False, null=False)
    STO = models.ForeignKey(STO, on_delete=models.CASCADE, related_name='reports')
    answers = ArrayField(AnswerField(), size=answer_no, blank=False, null=False) # here comes the problem

As you can see, each Report has an array of AnswerField (AnswerField is a custom field, I've omitted it because it's out of the scope of this question). The size of this array should be specified on the related STO class, on the answer_no field. I made this decision because this value is equals for each report of a given STO, so inserting that in each single report would lead to data duplication. I've tried to achieve this using a property, but Django complaints that he can't serialize properties when doing migration:

ValueError: Cannot serialize: <property object at 0x7faf02161ea0>
There are some values Django cannot serialize into migration files.
0

There are 0 best solutions below