Home > Software design >  Can't assign a valid instance to a FK relation when creating a related instance
Can't assign a valid instance to a FK relation when creating a related instance

Time:04-28

I have the following related models

class Period(models.Model):
    """
    A table to store all periods, one period equals a specific month
    """
    period = models.DateField()

    def __str__(self):
        return f'{self.period}'


class Payment(models.Model):
    """
    A table to store all payments derived from an offer
    """
    # Each monthly payment relates to an offer
    offer = models.ForeignKey(Offer, on_delete=models.CASCADE)
    month = models.ForeignKey(Period, on_delete=models.CASCADE)
    amount = models.PositiveIntegerField()
...

for key, value in payments.items():
    
    period = Period.objects.get_or_create(period=key)
    print(period)

    Payment.objects.create(
        offer=offer_instance,
        month=period,
        amount=value
    )

which raises

ValueError: Cannot assign "(<Period: 2022-05-01>, False)": "Payment.month" must be a "Period" instance.

although print(period) returns

(<Period: 2022-05-01>, False)

which to me looks like a valid instance?

CodePudding user response:

.get_or_create(…) [Django-doc] returns a 2-tuple with as first item the item that is retrieved/created, and as second item a boolean that indicates whether it was created. You thus should unpack the 2-tuple with:

for key, value in payments.items():
    period, __ = Period.objects.get_or_create(period=key)
    Payment.objects.create(
        offer=offer_instance,
        month=period,
        amount=value
    )
  • Related