11.6 交易记录
Last updated
Last updated
这两个条件应该是或者(or)的关系
# select * from drift where requester_id = ? or gifter_id = ?
# order by create_time desc
drifts = Drift.query.filter(
or_(Drift.requester_id == current_user.id,
Drift.gifter_id == current_user.id))\
.order_by(desc(Drift.create_time)).all()
Drift ViewModel需要适应当前用户是赠送者和当前用户是索要者两个情况
class DriftCollection:
def __init__(self, drifts, current_user_id):
self.data = []
self.data = self._parse(drifts, current_user_id)
def _parse(self, drifts, current_user_id):
return [DriftViewModel(drift, current_user_id).data for drift in drifts]
class DriftViewModel:
def __init__(self, drift, current_user_id):
self.data = {}
self.data = self._parse(drift, current_user_id)
@staticmethod
def requester_or_gifter(drift, current_user_id):
# 不建议将current_user耦合进DriftViewModel,破坏了封装性,难以扩展,所以当做参数从外部传入
return 'requester' if current_user_id == drift.requester_id else 'gifter'
def _parse(self, drift, current_user_id):
you_are = DriftViewModel.requester_or_gifter(drift, current_user_id)
# pending_status 设计到了4*2=8种状态,这个状态的判断应该在PendingStatus完成
pending_status = PendingStatus.pending_str(drift.pending, you_are)
r = {
'drift_id': drift.id,
'you_are': you_are,
'book_title': drift.book_title,
'book_author': drift.book_author,
'book_img': drift.book_img,
'date': drift.create_datetime.strftime('%Y-%m-%d'),
'operator': drift.requester_nickname if you_are != 'requester' \
else drift.gifter_nickname,
'message': drift.message,
'address': drift.address,
'status_str': pending_status,
'recipient_name': drift.recipient_name,
'mobile': drift.mobile,
'status': drift.pending
}
return r
enums.py
class PendingStatus(Enum):
Waiting = 1
Success = 2
Reject = 3
Redraw = 4
@classmethod
def pending_str(cls, status, key):
key_map = {
cls.Waiting.value: {
'requester': '等待对方邮寄',
'gifter': '等待你邮寄'
},
cls.Reject.value: {
'requester': '对方已拒绝',
'gifter': '你已拒绝'
},
cls.Redraw.value: {
'requester': '你已撤销',
'gifter': '对方已撤销'
},
cls.Success.value: {
'requester': '对方已邮寄',
'gifter': '你已邮寄,交易完成'
}
}
return key_map[status][key]
1.BookViewModel将单体和集合分开,单体定义实例属性,清晰明了(最推荐) 2.MyTrade 将单体作为字典融合在集合类里面,代码少,灵活性高,但是不易扩展(最不推荐) 3.DriftViewModel 将单体和集合分开,单体使用字典。坚固了前两中的优点,但是可读性下降(也不是特别推荐)