Answer the question
In order to leave comments, you need to log in
Many-to-many or ForeignKey?
My django project needs to implement api with get method.
Here is part of my code:
models.py:
class Color(models.Model):
temp = models.IntegerField(max_value=None, min_value=1)
correct = models.BooleanField()
top = models.IntegerField(max_value=None, min_value=1)
bottom = models.IntegerField(max_value=None, min_value=1)
class Speed(models.Model):
start = models.TimeField()
end = models.TimeField()
class Dog(models.Model):
name = models.CharField(max_length=50)
number = models.IntegerField(max_value=None, min_value=1)
speed = models.ForeignKey('Speed', on_delete=models.CASCADE, null=True, blank=True)
class DogRequest(models.Model):
id_name = models.IntegerField(max_value=None, min_value=1)
colors = models.ForeignKey('color', on_delete=models.CASCADE, null=True, blank=True)
dogs = models.ForeignKey('dog', on_delete=models.CASCADE, null=True, blank=True)
DataTime = models.DateTimeField()
class ColorSerilizer(serializers.Serializer):
temp = serializers.IntegerField(max_value=None, min_value=1)
correct = serializers.BooleanField()
top = serializers.IntegerField(max_value=None, min_value=1)
bottom = serializers.IntegerField(max_value=None, min_value=1)
class SpeedSerializer(serializers.Serializer):
start = serializers.TimeField()
end = serializers.TimeField()
class DogSerializer(serializers.Serializer):
name = serializers.CharField(max_length=50)
number = serializers.IntegerField(max_value=None, min_value=1)
speed = SpeedSerializer()
class DogRequestSerializer(serializers.Serializer):
id_name = serializers.IntegerField(max_value=None, min_value=1)
color = ColorSerilizer()
dog = DogSerializer()
DataTime = serializers.DateTimeField()
@csrf_exempt
def DogRequestApi(request, id=0):
if 'GET' == request.method:
DogRequests = DogRequest.objects.all()
DogRequest_serializer = DogRequestSerializer(DogRequests)
return JsonResponse(DogRequest_serializer.data, safe=False)
{
"id_name": 44,
"color": {
"temp": 33,
"correct": true,
"top": 33,
"bottom": 33,
},
"dog": {
"name": "bobi",
"number": 33,
"speed": {
"start": "10:07:21",
"end": "10:07:22"
}
},
"DataTime": "2022-02-11T10:07:29Z"
{
"id_name": 44,
"color": {
"temp": 33,
"correct": true,
"top": 33,
"bottom": 33,
},
"dog": [{
"name": "bobi",
"number": 33,
"speed": {
"start": "10:07:21",
"end": "10:07:22"
}
},
"DataTime": "2022-02-11T10:07:29Z"
}]...
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question