Vade
Vade

Reputation: 2039

data relationship modeling and Django

This question might be really easy but for the life of me i cant get my head around this today...

I have been asked by work to learn Django so i have donned my cap and been working on tutorials and the such the last couple of days. however i have a problem i could do with some help with.

I have this basic data model:

table1

Datasets - Id, Name

table2

subcatergory - id, dataset_id,name

table3

subcatergory value - id,subcat_id,value

so 1 dataset can have many subcatergories and 1 subcatergory can have many values.

in django i have this:

class Dataset(models.Model):
    name = models.CharField(max_length=150)
    def __unicode__(self):
        return self.name

class SubCat(models.Model):
    dataset = models.ForeignKey(Dataset)
    name = models.CharField(max_length=100)
    def __unicode__(self):
        return self.name

class SubCatVal(models.Model):
    subcat = models.ForeignKey(SubCat)
    value = models.CharField(max_length=100)

in the views.py when i am testing it (i am basically atm just wanting to fill some drop boxes) if i do d = Dataset.objects.all() then the object d have no knowlegde of the sub catergories?

so i if i wanted it all i would have to do:

d  = Dataset.objects.all();
s  = SubCat.objects.all();
sv = SubCatVal.objects.all();

then in the html do something like

{% for d in  dataset %}
    {% for s in subcat %}
        {% if s.dataset_id == d.id %}
            //add {{s.name}} to a select box
        {% endif %}
    {% endfor %}
{% endfor %}

is this the way to do this? or am i totally missing a trick?

thanks

Upvotes: 0

Views: 152

Answers (3)

tikider
tikider

Reputation: 550

read Related objects reference for how to store & retrieve related objects.

Upvotes: -1

jeffknupp
jeffknupp

Reputation: 6314

You can reference the foreign keys from Dataset with dObject.subcat_set.all(), which will list all of the subcategories for the dObject object. Similarly, you can get all the SubCatValues with subcatObject.subcatval_set.all(). This is a bit besides the point, though, as you should be creating forms programatically with a Form or ModelForm object, and not writing them yourself manually in the HTML.

Upvotes: 4

AdamKG
AdamKG

Reputation: 14091

Check out the docs on getting related objects:

https://docs.djangoproject.com/en/dev/ref/models/relations/ https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward

In short: yes, it'll be something like:

# in view, passed to template
datasets = Dateset.objects.all()
# template
{% for d in datasets %}
    {% for s in d.subcat_set.all %}
        <option value="{{ s.id }}">{{ s.name }}</option>
    {% endfor %}
{% endfor %}

Upvotes: 3

Related Questions