簡體   English   中英

如何在Django 1.8中創建可重用的函數以使用多個null值實施“ unique_together”?

[英]How can I create a reusable function to enforce “unique_together” in Django 1.8 with multiple null values?

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

我在元類上為模型上的兩個字段設置了unique_together。 它不能很好地工作,因為它不允許在field1和field2為空的多種情況下使用。 我需要這些字段都是可選的,或者如果一個字段具有值,那么另一個字段也必須具有值。 在一起,它們應該是唯一的(unique_together)

到目前為止,我的工作是荒謬和丑陋的。 我不知道如何更好或更有效地編寫它,但是很想學習如何以更Python化的方式進行編寫。

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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM