Added asset_id autofill for asset creation and duplication

This commit is contained in:
Matthew Smith
2019-10-14 15:50:05 +01:00
parent 64439ff53b
commit 8ec27eb075
2 changed files with 22 additions and 2 deletions

View File

@@ -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})

View File

@@ -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})