Skip to content Skip to sidebar Skip to footer

Access A Specific Item In Db In My For Statement

I have a somewhat odd scenario. I am using a read only database that I have access through my property management software. They allow the user to define fields in there software.

Solution 1:

It sounds like you are attempting to do this in a Django template. You should instead be using Python code, because Django templates are not designed for this.

The Django models for the table also won't provide the nicest interface for accessing these properties. Instead you should create some functions on top of them. Alternatively you could write raw SQL that do joins across the two tables.

Solution 2:

Using your models as they are (there are no ForeignKeys defined, so you can't use the ORM to follow relationships), you can get the details like this (if I understood your question correctly):

property = Property.objects.get(name='my_property_name') # or however you get the propertyprop_user_defined_values = Propuserdefinedvalues.objects.filter(propid=property.id, userdefinedid=49)

However, this could be shorted if you changed the order of your models, and some of your fields to type ForiegnKey:

classProperty(models.Model):
    # ... rest truncated ...classPropuserdefined(models.Model):
    # ... rest truncated ...classPropuserdefinedvalues(models.Model):
    property = models.ForeignKey(Property, db_column='propid')
    userdefined = models.ForeignKey(Propuserdefined, db_column='userdefinedid')
    # ... rest truncated ...

This would let you do something like:

Propuserdefinedvalues.objects.filter(userdefined__name='my_name', property__name='my_property')
# or:
my_property = Property.objects.get(name='my_property')
Propuserdefinedvalues.objects.filter(userdefined__userdefinedid=49, property=my_property)

I suggest you read about Django's models here: https://docs.djangoproject.com/en/1.5/topics/db/models/ - they're quite easy to get right, even if you have pre-existing tables, as long as you know the relationships.

(Disclaimer: untested code! May be bugs ;))

Post a Comment for "Access A Specific Item In Db In My For Statement"