Extract "limit_choices_to" options for relatedfields

- Specify as 'filters' for 'related field' type
- Extremely handy to be able to filter AJAX requests in a DRY manner!
This commit is contained in:
Oliver 2021-06-28 21:29:51 +10:00
parent f3ed05a09e
commit ac7564d069
3 changed files with 19 additions and 14 deletions

View File

@ -90,7 +90,7 @@ class InvenTreeMetadata(SimpleMetadata):
to any fields whose Meta.model specifies a default value
"""
field_info = super().get_serializer_info(serializer)
serializer_info = super().get_serializer_info(serializer)
try:
ModelClass = serializer.Meta.model
@ -100,7 +100,7 @@ class InvenTreeMetadata(SimpleMetadata):
# Iterate through simple fields
for name, field in model_fields.fields.items():
if field.has_default() and name in field_info.keys():
if field.has_default() and name in serializer_info.keys():
default = field.default
@ -110,27 +110,27 @@ class InvenTreeMetadata(SimpleMetadata):
except:
continue
field_info[name]['default'] = default
serializer_info[name]['default'] = default
# Iterate through relations
for name, relation in model_fields.relations.items():
if relation.reverse:
print("skipping reverse relation -", name)
if name not in serializer_info.keys():
# Skip relation not defined in serializer
continue
print('filters:', name, relation.model_field.get_limit_choices_to())
if relation.reverse:
# Ignore reverse relations
continue
continue
# Extract and provide the "limit_choices_to" filters
field_info[name]['filters'] = relation.model_field.get_limit_choices_to()
# This is used to automatically filter AJAX requests
serializer_info[name]['filters'] = relation.model_field.get_limit_choices_to()
except AttributeError:
pass
print(field_info.keys())
return field_info
return serializer_info
def get_field_info(self, field):
"""

View File

@ -45,6 +45,12 @@
method: 'POST',
title: '{% trans "Edit Part Details" %}',
fields: {
part: {
filters: {
}
},
quantity: {},
/*
name: {
onEdit: function() {
console.log('Edited name field');
@ -67,7 +73,6 @@
purchaseable: {},
salable: {},
component: {},
/*
'website',
'address',
'phone',

View File

@ -267,8 +267,8 @@ function constructFormBody(fields, options) {
// Copy custom options across to the fields object
if (field_options) {
// Query filters
fields[field].filters = field_options.filters;
// Override existing query filters (if provided!)
fields[field].filters = Object.assign(fields[field].filters || {}, field_options.filters);
// Secondary modal options
fields[field].secondary = field_options.secondary;