[Fixed]-Django: limiting model instance based on foregin key

1๐Ÿ‘

  1. If you want to do some custom validation, youโ€™d better do it via forms, or (as a last resort), using the Model.clean* methods family.

    class Campaign(models.Model):
        def clean(self):
            if self.pk:
                if self.item_set.count() > 5 # Or whatever number you need
                    raise ValidationError(_('Too much items for me.'))
    
  2. Override the get_extra() method for your inline:

    class ItemInline(admin.TabularInline):  
        extra = 4
        def get_extra(self, request, obj=None, **kwargs):           
            if obj:
                return obj.rows * obj.columns
            return self.extra
    
๐Ÿ‘คAlex Morozov

Leave a comment