I have this problem where I have a parent model User that is one-to-many linked to another model say Device.
What I want to do is within each user, I want to create and increment an id for each device he own.
Something like user A have two devices so his user_device_id will be 1 and 2. user B have one device so his user_device_id will be 1. vice versa.
I have a current working solution but I am looking for an alternative solution.
The Device model currently implemented which overrides save method:
class Device(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
user_device_id = models.PositiveIntegerField(default=0, null=false)
def save(self, *args, **kwargs):
try:
within_user_device_id = Device.objects.filter(user=self.user).latest('user_device_id').user_device_id
self.user_device_id = within_user_device_id + 1
except Device.DoesNotExist:
self.user_device_id = 1
For the neater method, in my mind, to create a function that gets the current instance of user and use the default in models.PositiveIntegerField to increment this value.
The problem is I cannot get refer the current instance and call the function in default.
class Device(models.Model):
def increment_within_user_device_id(self):
within_user_device_id = Device.objects.filter(user=self.user).latest('user_device_id').user_device_id
if not within_user_device_id:
return 1
else:
within_user_device_id += 1
return within_user_device_id
user = models.ForeignKey(User, on_delete=models.CASCADE)
# I cannot pass the function in default
user_device_id = models.PositiveIntegerField(default=increment_with_user_device_id(self), null=false)
Any ideas?