Skip to content

Commit

Permalink
Allow lookup with custom PK fields
Browse files Browse the repository at this point in the history
  • Loading branch information
SchrodingersGat committed May 14, 2024
1 parent a702b46 commit 32286d0
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 24 deletions.
51 changes: 27 additions & 24 deletions inventree/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,34 @@ class InventreeObject(object):

MODEL_TYPE = None

@classmethod
def getPkField(cls):
"""Return the primary key field name for this model.
The default value (used for most models) is 'pk'.
"""
return 'pk'

def getPkValue(self):
"""Return the primary key value for this model."""

return self._data.get(self.getPkField(), None)

@property
def pk(self):
"""Override the 'pk' property to return the primary key value for this object.
Note that by default this is the 'pk' field, but can be overridden in subclasses.
"""
return self.getPkValue()

def __str__(self):
"""
Simple human-readable printing.
Can override in subclass
"""

return f"{type(self)}<pk={self.pk}>"
return f"{type(self)}<{self.getPkField()}={self.pk}>"

def __init__(self, api, pk=None, data=None):
""" Instantiate this InvenTree object.
Expand All @@ -47,15 +68,9 @@ def __init__(self, api, pk=None, data=None):
# If the pk is not explicitly provided,
# extract it from the provided dataset
if pk is None and data:
pk = data.get('pk', None)

# Convert to integer
try:
pk = int(pk)
except Exception:
raise TypeError(f"Supplied <pk> value ({pk}) for {self.__class__} is invalid.")
pk = data.get(self.getPkField(), None)

if pk <= 0:
if type(pk) is int and pk <= 0:
raise ValueError(f"Supplier <pk> value ({pk}) for {self.__class__} must be positive.")

self._url = f"{self.URL}/{pk}/"
Expand Down Expand Up @@ -151,27 +166,15 @@ def fieldNames(cls, api):

return [k for k in cls.fields(api).keys()]

@property
def pk(self):
""" Convenience method for accessing primary-key field """
val = self._data.get('pk', None)

try:
val = int(val)
except ValueError:
pass

return val

@classmethod
def create(cls, api, data, **kwargs):
""" Create a new database object in this class. """

cls.checkApiVersion(api)

# Ensure the pk value is None so an existing object is not updated
if 'pk' in data.keys():
data.pop('pk')
if self.getPkField() in data.keys():
data.pop(self.getPkField())

response = api.post(cls.URL, data, **kwargs)

Expand Down Expand Up @@ -221,7 +224,7 @@ def list(cls, api, **kwargs):
response = response['results']

for data in response:
if 'pk' in data:
if cls.getPkField() in data:
items.append(cls(data=data, api=api))

return items
Expand Down
5 changes: 5 additions & 0 deletions inventree/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ class InvenTreePlugin(inventree.base.MetadataMixin, inventree.base.InventreeObje

URL = 'plugins'

@classmethod
def getPkField(cls):
"""Return the primary key field for the PluginConfig object."""
return 'key'

def setActive(self, active: bool):
"""Activate or deactivate this plugin."""

Expand Down

0 comments on commit 32286d0

Please sign in to comment.