我有一个名为已部署合同模型的模型,如下所示
function (doc) {
// Leidse plein
latitude = 52.3648111;
longitude = 4.8810906;
distance = Math.acos(
Math.sin(doc.latitude * Math.PI / 180) *
Math.sin(latitude * Math.PI / 180)
+
Math.cos(doc.latitude * Math.PI / 180) *
Math.cos(latitude * Math.PI / 180) *
Math.cos((doc.longitude - longitude) * Math.PI / 180)) * 6371;
// all poi's within 5km radius
if(distance <= 5 ) {
emit([doc.title,doc.latitude,doc.longitude], distance);
}
}
其中house_owner和house_tenant包含房主和房屋租户的电子邮件,它的序列化程序如下所示
from django.db import models
class DeployedContracts(models.Model):
house_no = models.CharField(max_length=200, blank=False, default='')
rent = models.IntegerField(blank=False)
security_deposit = models.IntegerField(default=0, blank=False)
house_owner = models.CharField(max_length=100, blank=False, default='')
house_tenant = models.CharField(max_length=100, blank=False, default='')
deployed_contract_address = models.CharField(max_length=100, blank='', default='')
def save(self, *args, **kwargs):
super(DeployedContracts, self).save(*args, **kwargs)
我想编写一个API视图,其中包含一个get方法,该方法将电子邮件作为参数并返回DeployedContract的所有对象,其中house_owner或house_tenant的电子邮件等于参数中提供的电子邮件。我怎么能在django做到这一点?
答案 0 :(得分:1)
您可以导入Q object并尝试此操作:
from django.db.models import Q
qs = DeployedContracts.objects.filter(
Q(house_owner__iexact=YOURPARAMETER) |
Q(house_tentant__iexact=YOURPARAMETER)
)
阅读文档了解更多信息。
答案 1 :(得分:1)
在get_queryset
功能中实施过滤部分。并且可以使用django模型Q object实现 OR 操作。
现在,如果您使用任何参数调用api,它将返回所有DeployedContracts。如果您传递任何电子邮件,这将返回所有过滤结果
from django.db.models import Q
from rest_framework.response import Response
from rest_framework.views import APIView
from deployedcontracts.models import DeployedContracts
class DeployedContractsList(APIView):
def get_queryset(self):
deployed_contracts = DeployedContracts.objects.all()
email = self.request.query_params.get('email')
if email:
deployed_contracts = deployed_contracts.filter(
Q(house_owner__iexact=YOURPARAMETER) |
Q(house_tentant__iexact=YOURPARAMETER)
)
return deployed_contracts
def get(self, request, format=None):
service_providers = self.get_queryset()
serializer = DeployedContractsSerializer(service_providers, many=True)
return Response(data=serializer.data)
答案 2 :(得分:1)
from rest_framework.response import Response
from rest_framework.views import APIView
from django.db.models import Q
class DeployedContractsAPI(APIView):
def get(self, request, *args, **kwargs):
email = request.data.get('email', None)
if email:
queryset = DeployedContracts.objects.filter(Q(house_owner=email) | Q(house_tentant=email))
serializer = DeployedContractsSerializer(queryset)
return Response(data=serializer.data)
return Response(data={"message": "email parameter not provided"})
您可以阅读有关Django Q expressions here