Reputation: 5960
I have a model like this:
class Offer(models.Model):
condition_products = models.ManyToManyField(
"shop.Product",
blank=True,
help_text="User needs to own at least one of these products.",
)
condition_owned_after = models.DateField(
blank=True,
null=True,
help_text="User needs to own at least one products after this date.",
verbose_name="Owned after date",
)
It's for a webshop where we can create offers with certain conditions. One of the conditions is that the user needs to already own one or more products, and a second condition is that this products needs to be owned after a certain date.
I want to add validation to the model so that condition_owned_after
can only be filled in when condition_product_variants
is not None. But when I try to access condition_product_variants
in the clean
method I get a ValueError from Django.
class Offer(models.Model):
# ...
def clean(self):
if self.condition_owned_after and not self.condition_products.all():
raise ValidationError(
{
"condition_owned_after": "Cannot set condition_owned_after without also setting condition_products"
}
)
def save(self, *args, **kwargs):
self.full_clean()
return super().save(*args, **kwargs)
This results in the following error:
ValueError: "<Offer: Offer object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used
I understand the error, but I don't understand how to work around it. How can I validate my model, when the validation depends on the value of this M2M field?
I know that I can create a ModelForm
and assign it to the ModelAdmin
and do the validation there, so at least adding items via the admin UI is validated. But that doesn't validate models getting created or saved outside of the admin UI of course.
Upvotes: 0
Views: 40