Django - 设计具有虚拟场景的模型? [英] Django - designing models with virtual fields?

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

问题描述



我想问一些关于最优雅的方法来设计具有虚拟场景的模型,重新建立在线商店,系统中的所有产品都由产品定义。

  class Product(models.Model):
#所有产品共享的通用字段
name = ...
brand = ...
price = ...

但是,这个商店会有很多与互相完全无关的产品类型,所以我需要一些方法来存储这些虚拟不同产品类型的字段(即MP3播放器的容量,一个书的页数,..)。



我可以想出我的原始Django技能的解决方案是远远不够完美:




  • 拥有一个custom_fields属性
    和中间表I
    手动管理(
    我的脸尖叫丑):)


  • 或从
    产品继承类与Python的
    危险的exec-eval语句(这太多
    很多voodoo魔术维护
    ,还将实现将
    需要知道Django内部结构)的飞行。




你在做什么?



TIA。

解决方案

产品有特色。

  (models.Model):
feature_name = models.CharField(max_length = 128)
feature_value = models.TextField()
part_of = models.ForeignKey(Product)

像这样。



只是功能列表。

  p =产品(iPhone,Apple,350)
p.save()
f = Feature(mp3 capacity,16Gb,p)
f.save()

如果需要,您可以在单独的表格中列出功能名称的主列表。不要过度分析功能。你不能对他们进行任何处理。你所做的就是呈现他们。


I'd like to ask about the most elegant approach when it comes to designing models with virtual fields such as below in Django...

Let's say we're building an online store and all the products in the system are defined by the model "Product".

class Product(models.Model):
    # common fields that all products share
    name = ...
    brand = ...
    price = ...    

But the store will have lots of product types completely unrelated with eachother, so I need some way to store those virtual fields of different product types (ie. capacity of a MP3 player, pagecount of a book,..).

The solutions I could come up with my raw Django skills are far from perfect so far:

  • Having a "custom_fields" property and intermediate tables that I manage manually. (screaming ugly in my face :))

  • Or inheriting classes from "Product" on the fly with Python's dangerous exec-eval statements (that is too much voodoo magic for maintenance and also implementation would require knowledge of Django internals).

What's your take on this?

TIA.

解决方案

Products have Features.

class Feature( models.Model ):
    feature_name = models.CharField( max_length=128 )
    feature_value = models.TextField()
    part_of = models.ForeignKey( Product )

Like that.

Just a list of features.

p= Product( "iPhone", "Apple", 350 )
p.save()
f= Feature( "mp3 capacity", "16Gb", p )
f.save()

If you want, you can have a master list of feature names in a separate table. Don't over-analyze features. You can't do any processing on them. All you do is present them.

这篇关于Django - 设计具有虚拟场景的模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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