Django 模型结构 - 最佳实践
对于一个小的免费水果网站,我有以下模型关系:
3 个类 - 苹果、草莓和位置
苹果和草莓列出了水果的所有“属性”:
class Apple(models.Model):
treeSize = ...
age = ...
class Strawberry(models.Model):
fieldArea = ...
现在我想记录水果的所有位置。到目前为止,我有一个包含苹果和草莓位置和属性的类,这使得外键保持在水果的种类上。但不可能是这样。 它看起来效率很低,尤其是。如果我添加多种其他水果类型。此外,我还需要检查每个位置是否至少有一个水果键。
class Location(models.Model):
lat = ...
lng = ...
appleType = models.ForeignKey(Apple, null = True)
strawberryType = models.ForeignKey(Strawberry, null = True)
是否有更好的方法来设计关系或模型结构? 解决这个问题的最佳实践是什么?
谢谢您的建议!
For a little free fruit site, I have the following model relationship:
3 classes - Apples, Strawberries, and Locations
Apples and Strawberries list all "properties" of the fruits:
class Apple(models.Model):
treeSize = ...
age = ...
class Strawberry(models.Model):
fieldArea = ...
Now I want to record all locations with the fruits. So far I have a class with locations and attributes for Apples and Strawberries, which keeps the ForeignKeys to the kind of fruits. But that can't be it. It looks very inefficient, esp. if I add multiple other fruit types. Also, I would need to check that each location has at least one of the fruit keys.
class Location(models.Model):
lat = ...
lng = ...
appleType = models.ForeignKey(Apple, null = True)
strawberryType = models.ForeignKey(Strawberry, null = True)
Is there a better way to design the relationships or the model structure?
What would be the best practice for this problem?
Thank you for your advice!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个完美的例子,您需要使用 通用关系< /a>.
您无需将外键存储到其中的每一个,而是存储内容类型 ID(识别草莓和苹果)和对象 ID。当然,您可以使用
Location
模型中的相关字符串按照自己的约定进行开发,但所有这些艰苦的工作都在 django 的内置 内容类型框架。This is a perfect case where you need to use the Generic Relations.
Instead of storing the Foreign Key to each one of those, you store the content type id (that recognizes Strawberries from Apples) and the object ids. You can of-course, develop this with your own conventions using the relevant strings within the
Location
model, but all that hard work is done for you in the django's built in Content Type Framework.