diff --git a/assets/models.py b/assets/models.py index 005beadd..603363d3 100644 --- a/assets/models.py +++ b/assets/models.py @@ -1,5 +1,5 @@ from django.core.exceptions import ValidationError -from django.db import models +from django.db import models, connection from django.urls import reverse from polymorphic.models import PolymorphicModel @@ -79,6 +79,22 @@ class Asset(models.Model): circuits = models.IntegerField(blank=True, null=True) cores = models.IntegerField(blank=True, null=True) + def get_available_asset_id(): + sql = """ + SELECT MIN(CAST(a.asset_id AS int))+1 + FROM assets_asset a + LEFT OUTER JOIN assets_asset b ON + (CAST(a.asset_id AS int) + 1 = CAST(b.asset_id AS int)) + WHERE b.asset_id IS NULL AND CAST(a.asset_id AS int) >= %s; + """ + with connection.cursor() as cursor: + cursor.execute(sql, [9000]) + row = cursor.fetchone() + if row[0] is None: + return 9000 + else: + return row[0] + def get_absolute_url(self): return reverse('asset_detail', kwargs={'pk': self.pk}) diff --git a/assets/views.py b/assets/views.py index c706f949..7a5eacbf 100644 --- a/assets/views.py +++ b/assets/views.py @@ -89,12 +89,16 @@ class AssetCreate(LoginRequiredMixin, generic.CreateView): def get_context_data(self, **kwargs): context = super(AssetCreate, self).get_context_data(**kwargs) - context["create"] = True context["connectors"] = models.Connector.objects.all() return context + def get_initial(self, *args, **kwargs): + initial = super().get_initial(*args, **kwargs) + initial["asset_id"] = models.Asset.get_available_asset_id() + return initial + def get_success_url(self): return reverse("asset_detail", kwargs={"pk": self.object.id})