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
12 changes: 12 additions & 0 deletions api/documents.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,13 @@ class PetES(Document):
})
type = fields.TextField(attr='type_to_string')

# 後來model新增的一些欄位
Copy link
Owner

Choose a reason for hiding this comment

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

這裡就不需要寫入欄位
僅會放入需要關聯的欄位

size = fields.TextField()
weight = fields.FloatField()
gender = fields.KeywordField()
is_neutered = fields.BooleanField()
rer = fields.FloatField()

class Index:
name = 'pet'
settings = {
Expand All @@ -71,6 +78,11 @@ class Django:
'name',
'birthday',
'content',
'size',
'weight',
'gender',
'is_neutered',
'rer'
]


Expand Down
14 changes: 13 additions & 1 deletion api/management/commands/recordListener.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
from django.core.management.base import BaseCommand
from PetMonitoringSystemBackend.settings import RABBITMQ_CONFIG
from api.management.commands.callback import recordCallBack, machineCallBack
from api.models import Pet


class Command(BaseCommand):
def handle(self, *args, **options):
from api.utils.Rabbitmqserver import RabbitmqServer
from api.management.commands.callback import recordCallBack,machineCallBack
from api.management.commands.callback import recordCallBack, machineCallBack
if RABBITMQ_CONFIG["enable"]:
rabbitmqClient = RabbitmqServer(
username=RABBITMQ_CONFIG["username"],
Expand All @@ -16,10 +18,20 @@ def handle(self, *args, **options):
)

rabbitmqClient.connect()

# Listen Record
rabbitmqClient.expense("distance/#", recordCallBack.distanceCallBack)
rabbitmqClient.expense("temperature/#", recordCallBack.temperatureAndHumidityCallBack)
rabbitmqClient.expense("weight/#", recordCallBack.weightCallBack)
rabbitmqClient.expense("water/#", recordCallBack.waterCallBack)
# Listen Machine
rabbitmqClient.expense("machine/status/#", machineCallBack.machineCallBack)

if recordCallBack.temperatureAndHumidityCallBack() > 27 or recordCallBack.temperatureAndHumidityCallBack() < 20:
zx32829601 marked this conversation as resolved.
Show resolved Hide resolved
raise Exception("abnormal temp")

if recordCallBack.weightCallBack() < 0:
raise Exception("less weight")

if recordCallBack.waterCallBack() < 0:
raise Exception("less water")
14 changes: 13 additions & 1 deletion api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,22 @@ def __str__(self):


class Pet(models.Model):
GENDER_CHOICES = [
('male', 'Male'),
('female', 'Female'),
('unknown', 'Unknown'),
]

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="寵物生日")
content = models.TextField(verbose_name="寵物敘述")

size = models.CharField(max_length=256, verbose_name="寵物大小") # 新增寵物大小欄位
weight = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="寵物重量") # 新增寵物重量欄位
gender = models.CharField(max_length=10, choices=GENDER_CHOICES, default='unknown', verbose_name="性別") # 新增性別欄位
is_neutered = models.BooleanField(default=False, verbose_name="是否結紮") # 新增結紮欄位
der = models.DecimalField(max_digits=6, decimal_places=2, default=0, verbose_name="每日能量需求") # der欄位
# External Columns
# chip_id = models.CharField(max_length=256,verbose_name="晶片編號")
# coat_color = models.CharField(max_length=256)
Expand All @@ -25,6 +35,7 @@ def __str__(self):
return f'{self.name} 照顧人:{self.keeper.username}: 寵物種類{self.type.typename}'



class Machine(models.Model):
name = models.CharField(max_length=255, verbose_name="機器名稱")
onlineStatus = models.BooleanField(default=False, verbose_name="上線狀態")
Expand All @@ -45,6 +56,7 @@ class Record(models.Model):
pet = models.ForeignKey(to=Pet, on_delete=models.CASCADE, verbose_name="寵物ID")
type = models.ForeignKey(to=RecordType, on_delete=models.CASCADE, verbose_name="記錄種類")
data = models.FloatField(null=True, blank=True, verbose_name="數據值")

# machine = models.ForeignKey(to=Machine, on_delete=models.CASCADE, verbose_name="機器編號")

def __str__(self):
Expand Down
46 changes: 43 additions & 3 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 @@ -68,6 +68,19 @@ class PetCreateAPIView(APIView):
'content': openapi.Schema(
type=openapi.TYPE_STRING
),
'size': openapi.Schema(
type=openapi.TYPE_STRING
),
'weight': openapi.Schema(
type=openapi.TYPE_NUMBER
),
'gender': openapi.Schema(
type=openapi.TYPE_STRING
),
'is_neutered': openapi.Schema(
type=openapi.TYPE_BOOLEAN
),

}
)
)
Expand All @@ -78,16 +91,28 @@ def post(self, request, *args, **kwargs):
petTypeId = request.data.get("type", 0)
birthday = request.data.get("birthday", datetime.date.today())
content = request.data.get("content", "")
size = request.data.get("size", "") # 取得新增欄位 size 的值
weight = request.data.get("weight", 0) # 取得新增欄位 weight 的值
gender = request.data.get("gender", "") # 取得新增欄位 gender 的值
is_neutered = request.data.get("is_neutered", False) # 取得新增欄位 is_neutered 的值

keeper = User.objects.get(pk=keeperId)
petType = models.PetType.objects.get(pk=petTypeId)

# 計算每日熱量需求DER
der = calculate_daily_energy_requirement(weight)

pet = models.Pet.objects.create(
name=name,
keeper=keeper,
type=petType,
birthday=birthday,
content=content
content=content,
size=size, # 使用新增欄位 size 的值
weight=weight, # 使用新增欄位 weight 的值
gender=gender, # 使用新增欄位 gender 的值
is_neutered=is_neutered, # 使用新增欄位 is_neutered 的值
der=der, # 儲存計算得到的 DER
)
return Response(data=petResponseConverter(pet), status=status.HTTP_201_CREATED)
except Exception as e:
Expand All @@ -99,8 +124,8 @@ class PetCountAPIView(APIView):
def get(self, request, *args, **kwargs):
petDict = dict()
for i in models.PetType.objects.all():
petDict[i.typename]= models.Pet.objects.filter(type=i.id).count()
return Response(data=petDict,status=status.HTTP_200_OK)
petDict[i.typename] = models.Pet.objects.filter(type=i.id).count()
return Response(data=petDict, status=status.HTTP_200_OK)


def petResponseConverter(pet: models.Pet):
Copy link
Owner

Choose a reason for hiding this comment

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

不需要這個 改用 Serializer 處理

Expand Down Expand Up @@ -128,3 +153,18 @@ def petTypeResponseConverter(petType: models.PetType):
else:
result = ""
return result


def calculate_resting_energy_requirement(weight):
fan9704 marked this conversation as resolved.
Show resolved Hide resolved
return 70 * (weight ** 0.75)


def calculate_daily_energy_requirement(weight, activity_level):
if activity_level == 'low':
return 1.2 * calculate_resting_energy_requirement(weight)
elif activity_level == 'moderate':
return 1.4 * calculate_resting_energy_requirement(weight)
elif activity_level == 'high':
return 1.6 * calculate_resting_energy_requirement(weight)
else:
raise ValueError("Invalid activity level")