Add support for auto_weight counter on choices when loading selection field from custom_fields.yml

This also fixes a bug when using the same value for 2 different custom fields breaks becuase it tries to
create a new CustomFieldChoice object instead of reusing the one that already exists.
This commit is contained in:
Grokzen 2018-04-18 18:51:04 +02:00
parent 19805a4312
commit 187c349fde
2 changed files with 23 additions and 7 deletions

View File

@ -40,6 +40,21 @@
# weight: 50
# - value: Fourth Item
# weight: 40
# selection_field_auto_weight:
# type: selection
# label: Choose between items
# required: false
# filterable: true
# weight: 30
# on_objects:
# - dcim.models.Device
# choices:
# - value: A
# - value: B
# - value: C
# - value: "D like deprecated"
# weight: 999
# - value: E
# boolean_field:
# type: boolean
# label: Yes Or No?

View File

@ -56,13 +56,14 @@ with open('/opt/netbox/initializers/custom_fields.yml', 'r') as stream:
custom_field.save()
for choice_details in cf_details.get('choices', []):
choice = CustomFieldChoice.objects.create(
for idx, choice_details in enumerate(cf_details.get('choices', [])):
choice, created = CustomFieldChoice.objects.get_or_create(
field=custom_field,
value=choice_details['value'])
if choice_details.get('weight', 0):
choice.weight = choice_details['weight']
value=choice_details['value'],
)
# Add weight after initial creation to fix a bug if you use the same 'value'
# for multiple custom fields.
choice.weight = choice_details.get('weight', idx * 10)
choice.save()
print("🔧 Created custom field", cf_name)