我在 FastAPI 上有以下 Tortoise 模型:
class Users(models.Model):
"""
The User model
"""
id = fields.CharField(pk=True, max_length=100)
#: This is a username
username = fields.CharField(max_length=20, unique=True)
name = fields.CharField(max_length=50, null=True)
email = fields.CharField(max_length=320, null=False)
friends: fields.ManyToManyRelation["Users"] = fields.ManyToManyField(
'models.Users', through='friendships', null=False, default=[]
)
class FriendRequest(models.Model):
requestor = fields.ForeignKeyField('models.Users', null=False, related_name='friendships_requestor')
requestee = fields.ForeignKeyField('models.Users', null=False, related_name='friendships_requestee')
created_at = fields.DatetimeField(auto_now=True)
accepted_at = fields.DatetimeField(null=True)
class Meta:
unique_together=(('requestor', 'requestee'))
UserOut_Pydantic = pydantic_model_creator(Users, name="UserOut", exclude=['posts', 'postss', 'email', 'commentss', 'userss'])
FriendRequestOut = pydantic_model_creator(FriendRequest, name="FriendRequestOut", exclude_readonly=True)
我想,在获取用户时,也能得到它的好友请求(他们请求与其他人请求成为好友的好友请求。)
我的 FastAPI 路由中的查询:
user = Users.filter(id=user_id).first()
user_pydantic = await UserOut_Pydantic.from_queryset_single(user)
生成的 UserOut 对象具有正确填充 FriendRequest 对象的字段friendships_requestor 和friendships_requestor。但是,这些 FriendRequest 对象不包括请求者和被请求者。(既不是 id 也不是 UserOut 对象)。我可以从当前用户的 id 中推断出两者之一,但真的很想知道如何包含它们?
样本输出:
[models.FriendRequest.leaf(id=3, created_at=datetime.datetime(2021, 9, 28, 16, 24, 13, 59434, tzinfo=<UTC>), accepted_at=None)]