3
我有一個unique_togeter = True的模型,我使用ModelForm來驗證它。如何驗證Tastypie中的唯一一起約束?
models.py
class Restrict(BaseModel):
user = models.ForeignKey(User)
title = models.ForeignKey('title')
active = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True, default=datetime.now())
updated = models.DateTimeField(auto_now=True, default=datetime.now())
class Meta:
ordering = ["id"]
db_table = "editor_restrict"
app_label = "geral"
unique_together = ('user', 'title')
resources.py
class TitleResource(ModelResource):
class Meta:
queryset = Titulo.objects.all()
always_return_data = True
fields = ['name']
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
fields = ['username', 'email', 'first_name']
authentication = Authentication()
authorization = Authorization()
always_return_data = True
filtering = {
'username': ALL,
}
class RestrictResource(ModelResource):
user = fields.ForeignKey(UserResource, attribute='user', full=True)
title = fields.ForeignKey(TitleResource, attribute='title')
class Meta:
authentication = Authentication()
authorization = Authorization()
queryset = Restrict.objects.all()
resource_name = 'restrict'
always_return_data = True
fields = ['user', 'title', 'active']
serializer = Serializer()
validation = FormValidation(form_class=RestrictForm)
filtering = {
'user': ALL_WITH_RELATIONS,
}
這是很好的工作,當我做這樣的一個POST:
curl -H 'Content-Type: application/json' -X POST --data '{"active": true, "title": "/api/v1/titulo/16/", "user":"/api/v1/user/52831/"}' 'http://localhost:8000/api/v1/restrict/'
的響應是狀態代碼:400錯誤請求,如預期。
但像這樣完整的用戶:
curl -H 'Content-Type: application/json' -X POST --data '{"active": true, "title": "/api/v1/titulo/16/", "user": {"username": "[email protected]", "email": "[email protected]", "first_name": "Johnny"}}' 'http://localhost:8000/api/v1/restrict/'
我得到TypeError異常int()函數參數必須是從Django的一個字符串或數字,而不是「字典」。
UserResource在所有CRUD中都工作得很好。
如果我脫離Model的unique_together,這個POST也可以正常工作。
我試過調試,但我無法弄清楚發生了什麼。
問題是:我如何驗證這種情況並返回正確的響應?
謝謝。