Tuesday 15 March 2011

Defining dependent Django Model Fields -



Defining dependent Django Model Fields -

i have define model 1 of fields depends on other.

i storing commodity trades, , grades of commodities vary based on kind of commodity. illustration if store coal , iron trade need specify quantity of each grade beingness traded.

example: {'grade–i':500, 'grade-ii':1000, 'washery-grade-i':0, 'washery-grade-ii':0, 'washery-grade-iii':100} {'fe 65%+':10, 'fe 60-65%':55,'fe 55-60%':0}

one possible approach storing commodity type charfield choices , serializing the grade quantity , storing jsonfield.

class traderetail (models.model): commodity_type = models.charfield(max_length=5, choices=(('co','coal'),('io','iron-ore'),('wti','wti'),), blank=false) grade_quantity = jsonfield()

my questions are:

a) neatest way create model?

b) how define relationships between grade_quantity , commodity_type generate appropriate forms obtain user inputs?

c) custom validations write sit down in clean() function?

if correctly problem, think more "django-compliant" define 2 models: 1 containing commodity_type, , 1 containing grade_quantity. then, can create foreign key in commodity_type link grade_quantity. general documentation, may read https://docs.djangoproject.com/en/1.7/topics/db/examples/one_to_one/

exemple:

class commodity (models.model): type = models.charfield(...) quantity = models.foreignkey('commodity') class grade (models.model): type = models.<your type adapted grade quantity field>

warning: haven't test exact example, looks you're trying achieve. have @ page https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey

for questions:

a) tips on how create models, see first links onetoone examples. usually, useful add together str(self) function displaying correctly name of model instance. read examples in django documentation have tips how correctly write model (usually define first fields, methods of models, , str method).

b) foreignkey field link between 2 models (onetoone). manytomany link exists manytomanyfield field (see https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/)

c) normally: yes. illustration propose may need write on different way validation developed.

django django-models

No comments:

Post a Comment