rau.Codes
rau.Codes

Reputation: 73

Django Model save methode

I trying to add a save method for an model:

def save(self, *args, **kwargs):
    if self.Position:
        ProductImages.objects.filter(Position=self.Position, ProductID=self.ProductID).update(
            Position=self.Position+1)

It is working fine, but if I have an Image in Position 1 and one in 2 and add another in Position 1 then I have 2 times Images in Position 2. Is there an uncomplicated way to check all Positions with the ProductID?

Upvotes: 0

Views: 47

Answers (1)

Abdul Aziz Barkat
Abdul Aziz Barkat

Reputation: 21822

Use F() expressions to update instances according to their own Position value:

from django.db.models import F

def save(self, *args, **kwargs):
    if self.Position:
        queryset = self.__class__._default_manager.filter(Position=self.Position, ProductID=self.ProductID)
        if self.pk:
            queryset = queryset.exclude(pk=self.pk)
        if queryset.exists():
            self.__class__._default_manager.filter(Position__gte=self.Position, ProductID=self.ProductID).update(Position=F('Position') + 1)
    super().save(*args, **kwargs)

Note: Ideally Field names should be in snake_case not PascalCase. So it should be position not Position.

Upvotes: 1

Related Questions