如何检查字段是否已经存在?

时间:2019-12-02 06:49:44

标签: django django-rest-framework python-3.6 serializer

我需要检查字段是否已经存在。如果该字段不存在,那么我需要创建一个新字段。就像预订系统上的可用性检查一样

我的模特

# Choices
time = [
    ('1', 'Morning'),
    ('2', 'Afternoon'),
    ('3', 'Evening'),
    ('4', 'Night'),
]

# Model
class Calender(models.Model):
    user = models.ForeignKey(AUTH_USER_MODEL,on_delete=models.SET_NULL)
    date = models.DateField()
    time = models.CharField(max_length=10, choices=time)
    location = models.CharField(max_length=32)

我的观点

class CheckAvailabilityAPIView(APIView):
    def post(self, request):
        date = request.data.get('date')
        time = request.data.get('time')
        location = request.data.get('location')

        calender = Calender.objects.all()
        for obj in calender:
            if obj.booked_date == date and obj.time == time and obj.location == location:
                return Response({'response': 'Already exist'})
        else:
            user_id = request.user.id
            user = User.objects.get(id=user_id)
            serializer = VendorsCalenderSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save(
                    user=user,
                    date=date,
                    time=time,
                    location=location

                )
                return Response({'response': 'Success', 'result': serializer.data})
            else:
                return Response({'response': 'Failed', 'error': serializer.errors},
                                status=status.HTTP_400_BAD_REQUEST)

有人可以帮我吗??

3 个答案:

答案 0 :(得分:1)

您可以尝试使用get_or_create()

类似的东西:

appointment, created = Calender.objects.get_or_create(
    user=user,
    date=date,
    time=time,
    location=location
)

Returns a tuple of (object, created), where object is the retrieved or created object and created is a boolean specifying whether a new object was created.

然后基于created,您可以返回自定义的响应。

参考:https://docs.djangoproject.com/en/2.2/ref/models/querysets/#get-or-create

也许他们是Calender中的错字。也许您是说Calendar

答案 1 :(得分:0)

更改日历= Calender.objects.all() 至 日历,结果= Calender.objects.get_or_create(booked_date =日期,section_timing =时间,位置=位置) 如果结果为True,则创建新的压光机

答案 2 :(得分:0)

您还可以使用过滤器:

calender = session.query(Calender).filter_by(**kwargs).first()
        if calender:
            return Response({'response': 'Already exist'})
        else: