2👍
Thanks all to help me find out my problem. My code was correct but I made a mistake in query. I am getting canteen_id value by assigning a variable CANTEEN_ID in settings.py and save it by save() method.
So, My query should be:
from projectdir.settings import CANTEEN_ID
def validate_unique(self,exclude=None):
qs = Inventory.objects.filter(canteen_id=CANTEEN_ID)
4👍
If you override validate_unique
method in your model you should call super
as you do in save/delete etc.
def validate_unique(self, exclude=None):
# custom logic
super(Inventory, self).validate_unique(exclude=exclude)
- [Django]-Why do chat applications have to be asynchronous?
- [Django]-Looking for read-write lock in Django using PostgreSQL, e.g., SELECT FOR SHARE
- [Django]-Django Generated polish plurals form in .po file not working
- [Django]-Django send_mail returns SMTPConnectError
- [Django]-Comparison between django-admin-tools and django-grappelli
2👍
Firstly, I think unique_together
should work with a one to one field. If you can create a simple test case that shows that it doesn’t, then it would be worth creating a bug report.
If you do want to check the unique constraint manually, don’t do it in the save()
method. The Django admin doesn’t expect a validation error to be raised in the save method, so you get the error. Instead, override the model’s clean
method, and do the check in. Model forms, including the ones in the Django admin, will call the clean method when processing the form data.
class Inventory(models.Model):
...
def clean(self):
qs = Inventory.objects.filter(canteen_id=self.canteen_id)
if self.pk is None:
if qs.filter(item=self.item).exists():
raise ValidationError("item already exists")
See the docs on validating objects for more info.
- [Django]-How to fetch last 24 hours records from database
- [Django]-Django 'instancemethod' object has no attribute '__getitem__'
- [Django]-Deploy Django\Tornado on Heroku
- [Django]-Missing mysql.sock; yielding OperationalError: (2002, "Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)")
- [Django]-How to set PYTHONPATH on web server
- [Django]-Is Docker an alternative for 'virtualenv' while develping Django project?
- [Django]-Python: Mock doesn't work inside celery task
- [Django]-Formatting Time Django Template