Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

models.py and documents.py expand #56

Merged
merged 13 commits into from
Sep 8, 2023
5 changes: 5 additions & 0 deletions api/documents.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,11 @@ class Django:
'name',
'birthday',
'content',
'weight',
'gender',
'is_neutered',
'activity_level',
'der'
]


Expand Down
15 changes: 15 additions & 0 deletions api/management/commands/callback/recordCallBack.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ def temperatureAndHumidityCallBack(topic: str, body: str, ch=None, method=None,
logger.info("[Humidity] Received " + str(data["Humidity"]))
# ch.basic_ack(delivery_tag=method.delivery_tag)
# machine = models.Machine.objects.get(name=data["machineId"])

# Check for abnormal temperature
temperature = float(data["Temperature"])
if temperature > 27 or temperature < 20:
raise Exception("溫度異常")

try:
machine = models.Machine.objects.get(name=topic.split("/")[1])
except models.Machine.DoesNotExist:
Expand All @@ -44,10 +50,19 @@ def temperatureAndHumidityCallBack(topic: str, body: str, ch=None, method=None,
def weightCallBack(topic: str, body: str, ch=None, method=None, properties=None):
data = json.loads(body)
logger.info("[Weight] Received " + str(data["Weight"]))

weight = float(data["Weight"])
if weight < 0:
raise Exception("進食問題")

# ch.basic_ack(delivery_tag=method.delivery_tag)


def waterCallBack(topic: str, body: str, ch=None, method=None, properties=None):
data = json.loads(body)
logger.info("[Water] Received " + str(data["Water"]))

water = float(data["Water"])
if water < 0:
raise Exception("攝取水量問題")
# ch.basic_ack(delivery_tag=method.delivery_tag)
25 changes: 0 additions & 25 deletions api/management/commands/recordListener.py

This file was deleted.

12 changes: 12 additions & 0 deletions api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,23 @@ def __str__(self):


class Pet(models.Model):
ACTIVITY_LEVEL = [
('low', 'Low'),
('moderate', 'Moderate'),
('high', 'High')
]

name = models.CharField(max_length=256, verbose_name="寵物名稱")
keeper = models.ForeignKey(to=User, on_delete=models.CASCADE, verbose_name="寵物照顧人")
type = models.ForeignKey(to=PetType, on_delete=models.CASCADE, verbose_name="寵物種類")
birthday = models.DateField(verbose_name="寵物生日", blank=True, null=True, default=datetime.date.today)
content = models.TextField(verbose_name="寵物敘述")
weight = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="寵物重量", default=0) # 新增寵物重量欄位
gender = models.BooleanField(default=False, verbose_name="性別") # 新增性別欄位
is_neutered = models.BooleanField(default=False, verbose_name="是否結紮") # 新增結紮欄位
activity_level = models.CharField(max_length=10,
choices=ACTIVITY_LEVEL, default='Low')
der = models.DecimalField(max_digits=6, decimal_places=2, default=0, verbose_name="每日能量需求") # der欄位
image = models.ImageField(upload_to=upload_to, blank=True, null=True)

# External Columns
Expand Down
37 changes: 33 additions & 4 deletions api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,35 @@ class PetRequestSerializer(serializers.ModelSerializer):

class Meta:
model = Pet
fields = ['id', 'name', 'keeper', 'type', 'birthday', 'content', 'image']
read_only_fields = ('id',)
fields = ['id', 'name', 'keeper', 'type', 'birthday', 'content', 'image', 'weight', 'gender',
'is_neutered', 'activity_level', 'der']
read_only_fields = ('id', 'der')

def calculate_resting_energy_requirement(self, weight):
return 70 * (weight ** 0.75)

def calculate_daily_energy_requirement(self, weight, activity_level):
activity_levels = {
'low': 1.2,
'moderate': 1.4,
'high': 1.6,
}

if activity_level not in activity_levels:
raise serializers.ValidationError("Invalid activity level")

levels = activity_levels[activity_level]
return levels * self.calculate_resting_energy_requirement(float(weight))

def create(self, validated_data):
weight = validated_data.get('weight', 0)
activity_level = validated_data.get('activity_level')

if activity_level:
der = self.calculate_daily_energy_requirement(weight, activity_level)
validated_data['der'] = der

return super().create(validated_data)


class PetSerializer(serializers.ModelSerializer):
Expand All @@ -34,7 +61,8 @@ class PetSerializer(serializers.ModelSerializer):

class Meta:
model = Pet
fields = ['id', 'name', 'keeper', 'type', 'birthday', 'content', 'image']
fields = ['id', 'name', 'keeper', 'type', 'birthday', 'content', 'image', 'weight', 'gender',
'is_neutered', 'activity_level', ]
read_only_fields = ('id',)
depth = 1

Expand All @@ -45,7 +73,8 @@ class PetUploadImageSerializer(serializers.ModelSerializer):
class Meta:
model = Pet
fields = ['id', 'image']
read_only_fields = ('id', 'name', 'keeper', 'type', 'birthday', 'content')
read_only_fields = ('id', 'name', 'keeper', 'type', 'birthday', 'content', 'weight', 'gender',
'is_neutered', 'activity_level', 'der',)
depth = 1


Expand Down
2 changes: 2 additions & 0 deletions api/views/petViews.py
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

這邊可以參考目前 Master branch 的寫法,先製作 Serializer(DTO 的概念),就不需要自行定義輸入資料

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

這些 low moderate high 已經說明在 Model 裡面 Django Model 是否會對於這些不相對應的值進行處理?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

still a problem

Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,5 @@ def post(self, request: Request, pk: int):
pet.image = request.FILES.get("image")
pet.save()
return Response(data=PetSerializer(pet).data, status=status.HTTP_200_OK)


Loading