unique_together on add case django admin

时间:2016-09-01 06:28:37

标签: python django django-models django-admin django-validation

I have a vendormenu and menu items are in inlines so on edit case it is working as expected for both unqiue_together but on add case the form display

{'__all__': [u'Menu price with this Menu and Unit already exists.']}

I just wanted to have unique menu and units but on adding the form with same units it display like mentioned above. My model looks like this:

class MenuPrice(models.Model):
    menu = models.ForeignKey(VendorMenu, related_name='MenuPrice')
    unit = models.CharField(
        max_length=10,
        choices=UNITS,
    )
def save(self, *args, **kwargs):
    self.validate_unique()
    super(MenuPrice, self).save(*args, **kwargs)

def validate_unique(self, *args, **kwargs):
    from django.core.exceptions import ValidationError
    super(MenuPrice, self).validate_unique(*args, **kwargs)
    qs = MenuPrice.objects.filter(menu=self.menu)
    ''' Here I don't know how to check the values submitted through the form. I can not check the unit cause it is not save to database yet. so IF is the confusion to show the error. qs is empty at this time.'''
    #if qs.filter(menu=self.menu).exists():
        # raise ValidationError({'unit':['Unit must be unique',]})
class Meta:
    unique_together = (('menu', 'unit'),)

I am bit new to Django. Please let me know what should I do to check the form submitted data so that I can compare the same units for that menu. Thanks in advance.

0 个答案:

没有答案