How to configure Tastypie to treat a field as unique? My expectation would be to get some non-500 error (maybe a 409 conflict?) As an answer, if I try to insert duplicate entries for a field marked as unique.
I looked through the docs and it looks like this should be obvious to me, but for some reason I am not getting the answer that I expect to see.
Here is a link to the documentation:
http://readthedocs.org/docs/django-tastypie/en/latest/fields.html?highlight=unique
Sample code is as follows:
urls.py
v1_api = Api(api_name='v1') v1_api.register(CompanyResource()) urlpatterns = patterns('', (r'^api/', include(v1_api.urls)), )
resource.py
class CompanyResource(ModelResource): CompanyName = fields.CharField(attribute='company_name') CompanyId = fields.CharField(attribute='company_id', unique=True) Contact = fields.CharField(attribute='contact') Email = fields.CharField(attribute='email') Phone = fields.CharField(attribute='phone') class Meta: queryset = Company.objects.all() authentication = BasicAuthentication() authorization = Authorization() allowed_methods = ['get', 'post']
models.py
class Company(models.Model): company_name = models.TextField(default=None, blank=True, null=True) company_id = models.CharField(default='', unique=True, db_index=True, max_length=20) contact = models.TextField(default=None, blank=True, null=True) email = models.EmailField(default=None, blank=True, null=True) phone = models.TextField(default=None, blank=True, null=True)
The error I get is the following: (using curl to get into my local service):
curl --dump-header - -H "Content-Type: application/json" -X POST --user user:password --data '{"CompanyName": "company", "CompanyId": "1234567890", "Contact": "John", "Email": " example@example.com ", "Phone": "555-555-5555"}' http://localhost:8000/api/v1/company/ HTTP/1.0 500 INTERNAL SERVER ERROR Date: Thu, 15 Sep 2011 18:25:20 GMT Server: WSGIServer/0.1 Python/2.7.1 Content-Type: application/json; charset=utf-8 {"error_message": "(1062, \"Duplicate entry '1234567890' for key 'api_company_company_id_uniq'\")", ...<snip>... raise errorclass, errorvalue\n\nIntegrityError: (1062, \"Duplicate entry '1234567890' for key 'api_company_company_id_uniq'\")\n"}
When I remove unique=True, db_index=True, from the company model, I do not get an Integrity error, but instead a new duplicate resource is created. Again, this is not the expected result, since I would expect a unique preliminary check of some validation and calling some answer not 500.