【问题标题】:How to validate unique together constraint in Tastypie?如何在 Tastypie 中验证唯一的共同约束?
【发布时间】:2014-01-29 09:33:42
【问题描述】:

我有一个 unique_togeter = True 的模型,我正在使用 ModelForm 来验证它。

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 BAD REQUEST。

但是像这样的完整用户:

curl -H 'Content-Type: application/json' -X POST --data '{"active": true, "title": "/api/v1/titulo/16/", "user": {"username": "johnny@mail.com", "email": "johnny@mail.com", "first_name": "Johnny"}}' 'http://localhost:8000/api/v1/restrict/'

我得到 TypeError Exception int() 参数必须是字符串或数字,而不是来自 django 的“dict”。

UserResource 在所有 CRUD 中也都能正常工作。

如果我从 Model 中删除 unique_together,这个 POST 也可以正常工作。

我尝试调试,但无法弄清楚发生了什么。

问题是:我如何验证这个案例并返回正确的响应?

谢谢。

【问题讨论】:

    标签: python django validation unique tastypie


    【解决方案1】:
    1. 可能的问题:唯一一起转换为 mysql 中的唯一约束,并且如果至少有一个列为空,则允许重复。
    2. 添加标题默认值,或限制为不为空(如果您允许为空,可能会导致 1.)。
    3. 尝试在 RestrictResource 保存中添加一些调试信息,这样您将看到哪个 dict 出现在foregn int 字段中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-08
      • 2013-05-21
      • 1970-01-01
      • 2015-04-13
      • 2013-01-06
      • 1970-01-01
      • 2019-02-24
      相关资源
      最近更新 更多