许多用户可以联系租金购买。我想显示已联系特定租金的所有用户的列表。我应该创建一个UserAPIView并在那里显示或显示RentDetail中的用户列表?哪一个是最好的设计?
这是我的模型和序列化器
class Rental(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=300, blank=False, null=False)
phone_number = models.PositiveIntegerField(null=False, blank=False)
class Contact(models.Model):
buyer = models.ForeignKey(User)
rental = models.ForeignKey(Rental, related_name="rent")
phone_number = models.PositiveIntegerField(null=False, blank=False)
buyer_choice = models.CharField(choices=BUYER_CHOICES, max_length=1, null=False, blank=False)
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'email',)
class RentalSerializer(serializers.ModelSerializer):
user = serializers.ReadOnlyField(source='user.username')
galleries = GallerySerializer(many=True)
class Meta:
model = Rental
fields = ('__all__')
class UserAPI(APIView):
def get(self, request, format=None):
"""
List all the users
"""
reply = {}
try:
users = User.objects.all()
reply['data'] = UserSerializer(users, many=True).data
except:
reply['data'] = []
return Response(reply, status.HTTP_200_OK)
class RentAPIView(APIView):
def get(self, request, token=None, format=None):
"""
Returns a list of rents (or just rent if token is given)
"""
reply = {}
try:
rents = Rental.objects.filter(user=request.user)
buyer_id = self.request.query_params.get('buyer_id', None)
if buyer_id:
print ('buyer_id', buyer_id)
rents = rents.filter(rent__buyer__id=buyer_id)
if token:
rent = rents.get(id=token)
reply['data'] = RentalSerializer(rent).data
else:
reply['data'] = RentalSerializer(rents, many=True).data
except Rental.DoesNotExist:
return error.RequestedResourceNotFound().as_response()
except:
return error.UnknownError().as_response()
else:
return Response(reply, status.HTTP_200_OK)