2013-02-12 12 views
6

モデルにdictフィールドを追加し、dictを管理者に表示し、管理者から編集できるようにします。例えばモデルフィールドとしてDict

、私は関係rel_score(= 0デフォルト)各関係のスコアである

dict = { 'sister' : rel_score, 'mother' : rel_score, 'father': rel_score}

を有します。このdictを私のモデルに保存して管理者に表示したいので、管理者の各関係にこれらのrel_scoreを割り当てることができます。

また、異なる要素にスコアを割り当て(優先順位付け)、割り当てられたスコアに応じて値を返す方法の例は、本当に役立ちます。

+1

が重複する可能性をモデル?](http://stackoverflow.com/questions/402217/how-to-store-a-dictionary-on-a-django-model) –

+0

その質問はかなり古いです。それ以来、djangoと利用可能なアプリの両方が大きく変化しています。そのため、今では新しいアプローチがあるかもしれません。 –

+0

dictを表すためにjson-fieldを使用できますか? https://github.com/bradjasper/django-jsonfield json modelfieldsを持つ他のアプリ: https://www.djangopackages.com/grids/g/json-fields/ –

答えて

2

DictFieldを使用することは実際にはできません。基礎となるデータベースは、そのタイプのデータ構造をサポートしないためです。

リレーションシップモデルとリレーションシップを既存のモデルに保存するためのRelationshipScoreモデルがあります(例としてuserを使用します)。例えば:

Class RelationshipScore(models.Model): 
    user = models.ForeignKey(User) 

    relationship = models.CharField(max_length=50, primary_key=True) 
    score = models.IntegerField() 

あなたはその後、値を取得するために、既存のモデルに機能を追加することができます。

class User(models.Model): 
    def get_relationship(self, rel): 
     return RelationshipScore.objects.get(relationship=rel, user=self) 
    def get_lowest_relationship(self): 
     return RelationshipScore.objects.filter(user=self).order_by("-score")[0] 
1

をDjangoの1.8のように、ユーザはまた、HStore fieldを使用するオプションを持っているpostgresに。

A field for storing mappings of strings to strings. The Python data type used is a dict. 
0

Postgresのユーザーがeasely jsonfieldを使用することができます。

from django.db import models 

from django.contrib.postgres.fields import JSONField 
import json 

class Yourmodel(models.Model): 
    name = models.CharField() 
    dict_json = JSONField(blank=True, null=True) 
    def __str__(self):    
     return self.name 

、アプリ内:Djangoの上の辞書を保存する[方法の

the_dict = {'a':1,'b':2} 
Yourmodel.dict_json = json.dumps(the_dict) 
Yourmodel.save() 

https://docs.djangoproject.com/es/1.9/ref/contrib/postgres/fields/#jsonfield

関連する問題