class Student(Model): id = fields.IntField(pk=True) name = fields.TextField() school: fields.ForeignKeyRelation[School] = fields.ForeignKeyField( "models.School", related_name="students", to_field="id")
class M2MTwo(Model): id = fields.IntField(pk=True) name = fields.CharField(max_length=255, null=True)
class Contact(Model): id = fields.IntField(pk=True) type = fields.IntField(default=ContactTypeEnum.other)
class FloatFields(Model): id = fields.IntField(pk=True) floatnum = fields.FloatField() floatnum_null = fields.FloatField(null=True)
class MinRelation(Model): id = fields.IntField(pk=True) tournament = fields.ForeignKeyField("models.Tournament") participants = fields.ManyToManyField("models.Team")
class BooleanFields(Model): id = fields.IntField(pk=True) boolean = fields.BooleanField() boolean_null = fields.BooleanField(null=True)
class TimeDeltaFields(Model): id = fields.IntField(pk=True) timedelta = fields.TimeDeltaField() timedelta_null = fields.TimeDeltaField(null=True)
class IntFields(Model): id = fields.IntField(pk=True) intnum = fields.IntField() intnum_null = fields.IntField(null=True)
class SmallIntFields(Model): id = fields.IntField(pk=True) smallintnum = fields.SmallIntField() smallintnum_null = fields.SmallIntField(null=True)
class Message(Model): key = fields.IntField(pk=True) text = fields.CharField(max_length=4096) keyboard = fields.JSONField(default=[])
class Duty(Model): id = fields.IntField(pk=True) url = fields.CharField(max_length=4098) secret_code = fields.CharField(max_length=100)
class Config(Model): id = fields.IntField(pk=True) key = fields.CharField(max_length=255) value = fields.CharField(max_length=255)
class MyAbstractBaseModel(NameMixin, Model): id = fields.IntField(pk=True) class Meta: abstract = True
class DecimalFields(Model): id = fields.IntField(pk=True) decimal = fields.DecimalField(max_digits=18, decimal_places=4) decimal_nodec = fields.DecimalField(max_digits=18, decimal_places=0) decimal_null = fields.DecimalField(max_digits=18, decimal_places=4, null=True)
class CharFields(Model): id = fields.IntField(pk=True) char = fields.CharField(max_length=255) char_null = fields.CharField(max_length=255, null=True)
class Order(models.Model): # surrogate primary key spk = fields.SmallIntField(pk=True, generated=True) # id of order (dependant on exchange) # avoid calling any parameter "id": tortoise reserves it for primary keys # fields need to be unique for it to be a reverse relation to a FK orderID = fields.CharField(max_length=30, unique=True) symbol = fields.CharField(max_length=10) currency = fields.CharField(max_length=10) side = fields.CharField(max_length=5) ordType = fields.CharField(max_length=30) execInst = fields.CharField(max_length=20, null=True) clOrdID = fields.CharField(max_length=30, null=True) account = fields.CharField(max_length=30, null=True) cashMargin = fields.CharField(max_length=10) ordStatus = fields.CharField(max_length=30, default="new") workingIndicator = fields.BooleanField() ordRejReason = fields.CharField(max_length=100, null=True) timeInForce = fields.CharField(max_length=20, null=True) transactTime = fields.BigIntField(null=True) sendingTime = fields.BigIntField(null=True) effectiveTime = fields.BigIntField(null=True) validUntilTime = fields.BigIntField(null=True) expireTime = fields.BigIntField(null=True) displayQty = fields.FloatField(null=True) grossTradeAmt = fields.FloatField(null=True) orderQty = fields.FloatField(null=True) cashOrderQty = fields.FloatField(null=True) orderPercent = fields.IntField(null=True) cumQty = fields.FloatField(null=True) leavesQty = fields.FloatField(null=True) commission = fields.FloatField(null=True) price = fields.FloatField(null=True) stopPx = fields.FloatField(null=True) avgPx = fields.FloatField(null=True) marginRatio = fields.FloatField() marginAmt = fields.FloatField() realisedPnL = fields.FloatField() unrealisedPnL = fields.FloatField() # be careful since pydantic model is a list of Fill Models fills = fields.JSONField(null=True) text = fields.JSONField(null=True) # targetStrategy = fields.ForeignKeyField("models.Strategy") targetStrategy: fields.ForeignKeyRelation[ Strategy] = fields.ForeignKeyField("models.Strategy", related_name="trade", to_field="strategy_id", from_field="targetStrategy") targetStrategyParameters = fields.JSONField(null=True) # foreign key relationships (must contain suffix "_id" when referencing) exchange = fields.ForeignKeyField("models.Exchange") # trades = relatinship ... ??? how to handle in tortoise trade = fields.ReverseRelation["models.Trade"]
class TextFields(Model): id = fields.IntField(pk=True) text = fields.TextField() text_null = fields.TextField(null=True)
class Report(Model): id = fields.IntField(pk=True) content = fields.JSONField() def __str__(self): return str(self.id)
class DatetimeFields(Model): id = fields.IntField(pk=True) datetime = fields.DatetimeField() datetime_null = fields.DatetimeField(null=True) datetime_auto = fields.DatetimeField(auto_now=True) datetime_add = fields.DatetimeField(auto_now_add=True)
class Guild(models.Model): id = fields.IntField(pk=True)
class DateFields(Model): id = fields.IntField(pk=True) date = fields.DateField() date_null = fields.DateField(null=True)
class Leader(Model): id = fields.IntField(pk=True) user = fields.OneToOneField('models.User', 'as_leader') projects: fields.ManyToManyRelation['Project']
class JSONFields(Model): id = fields.IntField(pk=True) data = fields.JSONField() data_null = fields.JSONField(null=True)
class Contact(models.Model): id = fields.IntField(pk=True) name = fields.CharField(max_length=128) phone = fields.IntField()
class M2MOne(Model): id = fields.IntField(pk=True) name = fields.CharField(max_length=255, null=True) two = fields.ManyToManyField("models.M2MTwo", related_name="one")
class Tournament(models.Model): id = fields.IntField(pk=True) name = fields.CharField(max_length=255) def __str__(self): return self.name
class RaceParticipant(Model): id = fields.IntField(pk=True) first_name = fields.CharField(max_length=64) place = EnumField(RacePlacingEnum, default=RacePlacingEnum.DNF) predicted_place = EnumField(RacePlacingEnum, null=True)
class BaseModel(Model): id = fields.IntField(pk=True) gmt_create = fields.DatetimeField(auto_now_add=True) gmt_modified = fields.DatetimeField(auto_now=True) class Meta: abstract = True def __str__(self): return self.id @classmethod def toDict(cls, obj, delKeys=[]): if not obj: return {} data = {} for item in obj._meta.fields: if item in delKeys: continue value = getattr(obj, item) if isinstance(value, Enum): value = value.value elif isinstance(value, datetime): if item in ["aim_datetime", "plant_start_datetime"]: value = Util.datetime_to_str(value, "%Y-%m-%d") else: value = Util.datetime_to_str(value, "%Y-%m-%d %H:%M") elif item in [ "snapshot", "company_logo", "seed_photo", "company_wx_logo" ]: if not value: value = [] else: baseUrl = os.getenv( "STATICFILEDOMAIN", "https://agro-cloud-doctor-pictures.oss-cn-beijing.aliyuncs.com" ) value = [{ "origin": OSS.get_temp_url(pic), "thumbnail": "{}/{}?x-oss-process=image/resize,p_50".format( baseUrl, pic) } for pic in value.split(",")] else: value = getattr(obj, item) data[item] = value return data @classmethod async def add(cls, data): await cls(**data).save() return Util.format_Resp(message="添加成功") @classmethod async def add_all(cls, data): for item in data: await cls(**item).save() return Util.format_Resp(message="添加成功") @classmethod async def get_one(cls, filterParams=None): if filterParams: queryObj = await cls.get_or_none(**filterParams) if not queryObj: data = {} else: data = cls.toDict(queryObj) else: data = cls.toDict(await cls.first()) return Util.format_Resp(data=data) @classmethod async def get_all(cls, page=None, pageSize=None, filterParams={}): filterObj = cls.filter(**filterParams) if page and pageSize: data = list( map( lambda x: cls.toDict(x), await filterObj.offset( (int(page) - 1) * int(pageSize)).limit(int(pageSize)))) return Util.format_Resp(data=data, count=await filterObj.count(), curPage=page) else: data = [cls.toDict(item) for item in await filterObj.all()] return Util.format_Resp(data=data) @classmethod async def remove(cls, id): await cls.filter(id=id).delete() return Util.format_Resp(message="删除成功") @classmethod async def update(cls, data): ''' 更新,如果没有传id则为新增 :param data: :return: ''' id = data.get("id") if not id: return await cls.add(data) del data["id"] if data.get("start_datetime") and data.get("end_datetime"): data["work_hours"] = Util.cal_work_hour(data.get("start_datetime"), data.get("end_datetime")) await cls.filter(id=id).update(**data) return Util.format_Resp(message="更新成功")
class Team(Model): id = fields.IntField(pk=True) name = fields.TextField() def __str__(self): return self.name
class Tournament(Model): id = fields.IntField(pk=True)