Provide model-level default function option

This commit is contained in:
Oliver 2021-11-08 13:30:59 +11:00
parent 8d5c3ab18a
commit b2ae346343
3 changed files with 33 additions and 5 deletions

View File

@ -98,7 +98,7 @@ class InvenTreeMetadata(SimpleMetadata):
Override get_serializer_info so that we can add 'default' values
to any fields whose Meta.model specifies a default value
"""
serializer_info = super().get_serializer_info(serializer)
model_class = None
@ -108,6 +108,13 @@ class InvenTreeMetadata(SimpleMetadata):
model_fields = model_meta.get_field_info(model_class)
model_default_func = getattr(model_class, 'api_defaults', None)
if model_default_func:
model_default_values = model_class.api_defaults(self.request)
else:
model_default_values = {}
# Iterate through simple fields
for name, field in model_fields.fields.items():
@ -123,6 +130,9 @@ class InvenTreeMetadata(SimpleMetadata):
serializer_info[name]['default'] = default
elif name in model_default_values:
serializer_info[name]['default'] = model_default_values[name]
# Iterate through relations
for name, relation in model_fields.relations.items():
@ -141,6 +151,9 @@ class InvenTreeMetadata(SimpleMetadata):
if 'help_text' not in serializer_info[name] and hasattr(relation.model_field, 'help_text'):
serializer_info[name]['help_text'] = relation.model_field.help_text
if name in model_default_values:
serializer_info[name]['default'] = model_default_values[name]
except AttributeError:
pass

View File

@ -47,7 +47,7 @@ def get_next_build_number():
"""
if Build.objects.count() == 0:
return
return '0001'
build = Build.objects.exclude(reference=None).last()
@ -100,13 +100,28 @@ class Build(MPTTModel, ReferenceIndexingMixin):
return reverse('api-build-list')
def api_instance_filters(self):
return {
'parent': {
'exclude_tree': self.pk,
}
}
@classmethod
def api_defaults(cls, request):
"""
Return default values for this model when issuing an API OPTIONS request
"""
defaults = {
'reference': get_next_build_number(),
}
if request and request.user:
defaults['issued_by'] = request.user.pk
return defaults
def save(self, *args, **kwargs):
self.rebuild_reference_field()

View File

@ -37,7 +37,7 @@ def get_next_po_number():
"""
if PurchaseOrder.objects.count() == 0:
return
return '0001'
order = PurchaseOrder.objects.exclude(reference=None).last()
@ -66,7 +66,7 @@ def get_next_so_number():
"""
if SalesOrder.objects.count() == 0:
return
return '0001'
order = SalesOrder.objects.exclude(reference=None).last()