简体   繁体   中英

How to check if the value of a field has been deleted in Python/ Django

I'm trying to check if a value of field has been deleted and then return False or True if all the fields contain values.

My code actually doesn't check the value in the fields but just checks if the fields exists.

How to check the values of every specific field?

This is my models and in my views I have to check the function.

# models.py
class CompanyDirector(models.Model):
    username = models.CharField(max_length=128, blank=True, null=True)
    directorTitle = models.CharField(max_length=8, blank=True, null=True)
    directorName = models.CharField(max_length=64, blank=True, null=True)
    directorSurname = models.CharField(max_length=64, blank=True, null=True)
    directorId = models.CharField(max_length=16, blank=True, null=True)  
    proffessionStartDate = models.DateTimeField(blank=True, null=True)

# views.py
ret = {'complete': False}
  try:
      company_director = 
 CompanyDirector.objects.filter(company__token=token).first()
      if company_director:
        ret['complete'] = True
        for field in company_director._meta.get_all_field_names():
          if not getattr(company_director, field):
            ret['complete'] = False
            break;
  except ValueError as e:
     print (e)
  return Response(ret)

Get the values from the queryset, which will be a dict object.

Solution :

company_director = CompanyDirector.objects.filter(company__token=token).values().first()
if company_director:
    for field, value in company_director.items():
        if value is None:
            return False
    return True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM