Is it possible to require at least one ManyToOne instance to a model when it's (first) saved? The idea is, to have a product that can have a price history (hope using a separate, loosely-coupled model for this is the right approach); so in order to add a product, at least one price should be required.
I read that it's smarter to put this kind of validation into clean rather than save, as ValidationErrors are not raised from the latter and it's simply "better by convention". Not 100% sure where to draw the line regarding those two methods yet though.
Currently trying to get it to work with Django admin; code looks as follows
# models.py
class Product(models.Model):
name: str = models.CharField(max_length=128)
def clean(self):
if self._state.adding:
if not self.prices.count():
raise ValidationError({
'prices': ('At least one product price is required'),
})
class ProductPrice(models.Model):
product: Product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='prices')
price: float = models.FloatField()
created: datetime = models.DateTimeField(auto_now_add=True)
# admin.py
class ProductPriceInline(admin.TabularInline):
readonly_fields = ('created',)
model = ProductPrice
extra = 3
can_delete = False
@admin.register(Product)
class ProductInline(admin.ModelAdmin):
model = Product
verbose_name = 'Product'
inlines = [ProductPriceInline,]
And getting ValueError ProductForm has no field named prices. Also tried using a constraint on Product instead (models.CheckConstraint(check=~Q(prices=None), name='at_least_1_non_null'),]) but tbh I'm just really overwhelmed with all the different solution possibilities, finding the right one and/or finding out how I can fix what's wrong with the current one. Really glad for any pointers besides the main issue here.
edit: on a side note – just realized the clean method will always return self.prices.count() with 0, as the ProductPrice instance is only created after Product has been created and can therefore be referenced by the former.