django模型和OOP设计 [英] django models and OOP design

查看:95
本文介绍了django模型和OOP设计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个在线游戏的追求系统。我的任务序列化为一个JavaScript客户端的 json对象,然后从REST后端获取这些任务(我使用django RestFramework)



现在我想知道哪个 class django model 我应该把所属的行为数据。



我在几个不同的模型中存储属于任务的数据:
A model QuestHistory :with models.Fields like 布尔型已完成 Datetime开始我把信息属于一个特定的用户(也是一个字段用户)。



然后我有一个模型QuestTemplate :总是相同的部分,像 quest_title quest_description



我还有一个模型奖励模型任务和TaskHistory 外键字段链接到任务。



要将此信息结合到任务中,我创建了一个纯python 类Quest(object):和定义的方法这个类喜欢 check_quest_completion 。这个类是后来序列化的。这种方法的问题是它变得相当冗长,例如当我实例化这个类或当我定义Serializer。



是否有一个python或django快捷方式将 django模型的所有字段放入另一个类(我的任务类在这里),类似于 dict.update 方法的方法呢?



或者我应该尝试将方法放在模型上,并摆脱任务课程



我在游戏中还有其他一些与查询系统非常相似的地方,例如库存系统,所以我希望有一个更优雅的解决方案。 >

解决方案

您应该将Quest类的方法放在模型本身上,并摆脱Quest类。


I wrote a quest system for an online game. My quests are serialized into json objects for a JavaScript client that fetches those quests then from a REST backend (I use django RestFramework)

Now I'm wondering on which class or django model I should put the "behaviour" that belongs to the data.

I stored the data that belongs to a quest in several separate models: A model QuestHistory: with models.Fields like Boolean completed, and Datetime started where I put the information belonging to a specific user (it also as a field user).

Then I have a model QuestTemplate : The part that is always the same, fields like quest_title and quest_description

I also have a model Rewards and model Task and TaskHistory that are linked to a quest with a foreign Key field.

To combine this information back to quest I created a pure python class Quest(object): and defined methods on this class like check_quest_completion. This class is the then later serialized. The Problem with this approach is that It becomes quite verbose, for example when I instantiate this class or when I define the Serializer.

Is there a python or django "shortcut" to put all fields of a django model into another class (my Quest class here), something similar to the dict.update method maybe?

Or should I try to put the methods on the models instead and get rid of the Quest class?

I have some other places in my game that look very similar to the quest system for example the inventory system so I'm hoping for a more elegant solution.

解决方案

You should put the methods of the Quest class on the model itself and get rid of the Quest class.

这篇关于django模型和OOP设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆