'Automatic Ordinal Number in django queryset ? How to sort this thing in Django?
I have problem to sort such thing as 'Ordinal Number'.
For example, I have my Parent Model (Order) and child (Item). I don't know how make Items ID field starting from 1 to N where N is number of items in this particullar Order. It's hard to explain for me , so I put some img with things I want to make and try to explain it by example.
And those are my models.py:
class Order(models.Model):
PENDING = 0
DURING = 1
DONE = 2
STATUS = (
(PENDING, 'Oczekuję'),
(DURING, 'W trakcie'),
(DONE, 'Zakończone'),
)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='order_user')
date_created = models.DateTimeField(auto_now_add=True, null=True)
slug = RandomSlugField(length=7, exclude_lower=True, exclude_upper=True, exclude_vowels=True)
status = models.SmallIntegerField(choices=STATUS, default=PENDING)
class Meta:
verbose_name = "zamówienie"
verbose_name_plural = "zamówienia"
def __str__(self):
return "Zamówienie ID#{} z dnia {}".format(self.slug, self.date_created.strftime('%d/%m/%y'))
def get_absolute_url(self):
return reverse('detail', kwargs={'slug': self.slug})
class Item(models.Model):
order = models.ForeignKey(Order, null=True, on_delete=models.SET_NULL)
lenght = models.DecimalField(max_digits=4, decimal_places=0)
width = models.DecimalField(max_digits=4, decimal_places=0)
lenght = models.PositiveSmallIntegerField(blank=False)
quantity = models.SmallIntegerField(default=1, blank=False, null=False)
description = models.CharField(max_length=255, blank=True, null=True)
lenght1 = models.BooleanField(default=False)
lenght2 = models.BooleanField(default=False)
width1 = models.BooleanField(default=False)
width2 = models.BooleanField(default=False)
class Meta:
verbose_name = "formatka"
verbose_name_plural = "formatki"
def __str__(self):
return "{} x {}".format(self.width, self.lenght)
Solution 1:[1]
#Make items ID count from 1 for each Order
for index, i in enumerate(item):
i.id = index + 1
i.save()
The solution is to use enumarte(), example for my code above. Where index is a number off element in list, as usually counting from 0. So we need do index + 1, to start counting from 1. And finally we do i.save(), to save it updated to db.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | buckwheattN1 |
