Thursday, December 22, 2016

Re: How can I access field values generically?

Ill be honest, I'm still not getting how your models are structured. That is ok though, I can give you some pointers and hopefully  that will be sufficient. I'll also be very explicit in describing the steps. Several are probably better as single orm calls. _meta docs at https://docs.djangoproject.com/en/1.10/ref/models/meta/

Hope this helps. If you have any clarifying questions I am happy to chime in more.

from django.db.models import TextField
#First get all ingredients you are interested in (I am assuming that
#mixtures are only one level deep, if not then build a recursive call)
ingredients
= Substance_Ingredients.objects.filter(substance=<parent substance>).values_list('ingredient.pk', flat=True)
#Get the substance instances for these
child_substances
= Substance.objects.filter(pk__in = ingredients)
target_text
= ''
for cs  in child_substance:
   
#Get all OneToOne and OneToMany fields

    models
=  [
       
(f, f.model if f.model != (Substance or SubstanceIngredient) else None)
       
for f in Substance._meta.get_fields()
       
if (f.one_to_many or f.one_to_one)
       
and not f.auto_created and not f.concrete
   
]
   
    ingredient_text
= ''
   
for field, model in models:
       
#Check the model for TextFields
        tfs
= [f for f in model._met.get_fields() if isinstance(f, TextField)]
       
#get the textfield attributes for your substance field
        field_text
= [getattr(field, tf, '') for tf in tfs]
       
#compile you text strings at the necessary levels
        ingredient_text
= '{}, {}'.format(ingredient_text, '.'.join(field_text))

    child_text
= '{}: {}'.format(cs.substance_name, ingredient_text)
    target_text
= '{}\n{}'.formate(target_text, child_text)

#Save you target text to the original substance


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/b39f85e3-1ecc-4a2f-93e7-f6f426a63520%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment