python - 如何创建一个可重用函数来强制 Django 1.8 中的 "unique_together"具有多个空值?

标签 python django rest

我正在使用 django 1.8 和带有角度前端的 REST 3.0。

我已在模型上的两个字段的元类上设置了 unique_together。 它不能很好地工作,因为它不允许 field1 和 field2 为 null 的多种情况。 我需要这些字段都是可选的 或者如果一个有值,那么另一个也必须有值。 它们在一起应该是唯一的 (unique_together)

到目前为止我所拥有的都是荒谬和丑陋的。我不知道如何更好或更有效地编写它,但很想学习如何以更 Pythonic 的方式做到这一点。

data = json.loads(request.body)
#field1 and field2 are nested in an array that is only POSTed if it exists. 

if 'key' in 'data':
    field1 = data[key].get(field1,"")
    field2 = data[key].get(field2,"")

elif 'key' not in 'data':
   field1 = "" 
   field2 = ""

if field1=="" and field2=="":
   field1 = None
   field2 = None

elif (field1 == "") and (field2 != ""):
   data.errors += 'You added field 2 but did not add field 1.'

elif (field1 !="") and (field2 ==""):
   data.errors += 'You added field 1 but did not add field 2.'

elif (field1 = "") and (country_code!=""):
   try:
       field1Db = [model].objects.get(field1=field1)
   except [model].DoesNotExist:
       valid_field1 = True
   else:
       if field1Db and ((field1Db.field2)) == (field2):
       data.errors += Field 1 + 'and' + Field 2 + 'should form a unique set if both are submitted.'
else:
   data.errors = False
   data.success = True
   return Response(data)

看起来可行,只是丑陋。

此后,我将数据发送到序列化器。 不管怎样,如果有人知道如何更有效地做到这一点,我真的很感激学习如何做。谢谢。

最佳答案

在提供两个值时,使用unique_together 验证情况。然后向您的模型添加一个 clean 方法,以确保要么提供两个值,要么都不提供。

class MyModel(models.Model):
    ... 
    def clean(self):
        """
        Make sure that if field1 or field2 is specified, 
        then they are both specified.
        """
        if self.field1 is not None and self.field2 is None:
            raise ValidationError('you must specify field2 if you specify field1')
        elif self.field1 is None and self.field2 is not None:
            raise ValidationError('you must specify field1 if you specify field2')

关于python - 如何创建一个可重用函数来强制 Django 1.8 中的 "unique_together"具有多个空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31062785/

相关文章:

python - Django Rest Framework——如何获取urls.py中的Http头信息

django - PlaceholderAdmin throws <lambda>() 仅接受 1 个参数(给定 2 个参数)

java - “网络错误: 415 Unsupported Media Type

python - 如何搜索匹配的字符串,然后提取其后面的字符串和冒号

python - 为什么相同数据的 scipy.stats.gaussian_kde() 比 seaborn.kde_plot() 慢?

python - Bootstrap 表单中带有外键的 Django 下拉菜单

Java Rest - 使用 GET 方法发送参数化列表

python - 使用 psycopg2 将 PostgreSQL UUID 数组作为列表返回

python - 如何在 Python 中仅提取 url 的特定部分并将其值添加为 df 中每一行的另一列?

azure - 使用 Microsoft Azure 认知服务 API 收到 401/404 错误