![](/img/trans.png)
[英]How to implement multiple user types with different roles and permissions in Django?
[英]How do you implement multiple data types for an object in Django?
我想知道將各種數據類型與Django中的對象相關聯的最佳方法。 其中一些類型應該是字符串,布爾值,圖像文件,從列表中選擇或鏈接。 例如,假設您有一個產品模型。 對於產品X,您需要添加一個圖像屬性,一個模型名稱字符串和一個鏈接。 對於產品Y,可能的屬性將是圖像,權重十進制。 進行此設置的最佳方法是什么? 是否有可用的軟件包來執行此操作或類似的操作?
您可以創建一個模型,為每個字段提供空白/空值。 或者,如果要設置具有相似期望屬性或屬於類別的產品類型,請使用django的模型繼承。 似乎您在詢問可選屬性,這些屬性僅需要您在模型中定義可選字段(第一個示例)。
沒有繼承:
class Product(models.Model):
name = models.CharField()
image = models.ImageField(blank=True, null=True)
weight = models.DecimalField(blank=True, null=True)
繼承ref
:
class Product(models.Model):
name = models.CharField()
class Meta:
abstract = True
class ProductTypeA(Product):
image = models.ImageField()
class ProductTypeB(Product):
weight = models.DecimalField()
編輯:
class Product(models.Model):
name = models.CharField()
class ProductImage(models.Model):
product = models.ForeignKey(Product)
image = models.ImageField()
class ProductWeight(models.Model):
product = models.ForeignKey(Product)
weight = models.DecimalField()
class ProductURL(models.Model):
product = models.ForeignKey(Product)
url = models.URLField()
class ProductFile(models.Model):
product = models.ForeignKey(Product)
file = models.FileField()
ProductXXXXX通過外鍵與Product型號相關。 這是一對多的關系,因此對於每個產品,您可以擁有多個productxxxx。
例如,您可以制作產品:
product_one = Product(name="product_one")
product_one.save()
現在,您要為該產品添加權重:
weight = ProductWeight(product=product_one, weight=3.55)
weight.save()
要查看與產品相關的所有重量:
product_one_weights = product_one.weight_set.all()
for weight in product_one_weights:
print weight
這使您可以擁有具有不同“屬性”的產品。
product_one
|
-----------------------------------------
| | | |
ProductWeight ProductImage ProductImage ProductFile
product_two
|
--------------
| |
ProductURL ProductImage
具有基於類型的結構的RDBMS並非為此目的而設計。 例如,以Google的大桌子為例,它不會抱怨您存儲的內容(即,產品A的屬性類型可能與產品B完全不同,盡管兩者的類型均為Product)。
您需要具有類型靈活性的基於對象的存儲系統。
您確定要不惜一切代價嗎? 我們仍然可以做到這一點,但是會產生很多開銷。 這是偽代碼。
Model Product: id (primary key) Model AttributeType: """ Defines various data types available for storage. ex: (1, 'INT') or (2,'STRING') or (3, 'FLOAT') """ id: name: Model ProductAttributes: """ Stores various attributes of a product Ex: (P1,ATT1,100) or (P1, ATT3, 10.5) or (P2, ATT2, "ABCD") """ FK-> Product FK-> AttributeType Name 'String' Value Blob
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.