inventree / inventree-python

Python library for communication with inventree via API
https://docs.inventree.org/en/latest/api/python/python/
MIT License
27 stars 35 forks source link

How to check if a parameter already exists in API #239

Closed realstudent01 closed 2 months ago

realstudent01 commented 2 months ago

From my script I want to see if a parameter already exists for a specific part. If it does, I'd like to modify the value.

I can call param = Parameter.create(api, { 'part': part, 'template': 150, 'data': 100}) the first time to create the parameter, but how can I see if that parameter already exists so that I don't execute the above line again and hit the following error: method: post, status_code: 400, body: {"non_field_errors":["The fields part, template must make a unique set."]}

SchrodingersGat commented 2 months ago

You can filter the API by 'part' and 'template' values, to see if it already exists.

from inventree.api import InvenTreeAPI
from inventree.part import Parameter

HOST = "https://demo.inventree.org"
USER = "steven"
PASS = "wizardstaff"

api = InvenTreeAPI(HOST, username=USER, password=PASS)

PART_ID = 1
TEMPLATE_ID = 3

# Find a matching template
template = Parameter.list(api, part=PART_ID, template=TEMPLATE_ID)

# Any exist?
if len(template) > 0:
    template = template[0]
    print("Found existing template:", template)
else:
    # Create a new one
    template = Parameter.create(api, part=PART_ID, template=TEMPLATE_ID, data="42")
    print("Created new template:", template)
> Found existing template: <class 'inventree.part.Parameter'><pk=3>
realstudent01 commented 2 months ago

Thanks!