I have created a validate_unique based on two fields (asset and portfolio), it works well when I try to create a new object that already exists, i get the correct message.
But i get the same error message if i try to update an existing object. Should i change something to make the update work?
class PortfolioAsset(models.Model):
portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1)
asset = models.ForeignKey(Asset, on_delete=models.CASCADE)
shares_amount = models.FloatField()
share_average_price_brl = models.FloatField()
total_cost_brl = models.FloatField(editable=False)
total_today_brl = models.FloatField(editable=False)
def validate_unique(self, *args, **kwargs):
super().validate_unique(*args, **kwargs)
if self.__class__.objects.filter(
portfolio=self.portfolio,
asset=self.asset
).exists():
raise ValidationError(
message='This asset already exists in this portfolio.',
code='unique_together',
)
def save(self, *args, **kwargs):
self.total_cost_brl = round(self.shares_amount * self.share_average_price_brl, 2)
self.total_today_brl = round(self.shares_amount * self.asset.price, 2)
super(PortfolioAsset, self).save(*args, **kwargs)
CodePudding user response:
you could exclude the id of the current instance in the case of update:
if self.__class__.objects.\
filter(portfolio=self.portfolio, asset=self.asset).\
exclude(id=self.id).\
exists():
CodePudding user response:
You should exclude currant instance
from django.db.models import Q
if self.__class__.objects.filter(portfolio=self.portfolio, asset=self.asset).filter(~Q(id=self.id)).exists():