azmeuk
azmeuk

Reputation: 4516

Inverted foreign-key relation in django admin

I have two classes with a simple one-to-many relation.

models.py

class Bar(models.Model):
  label = models.CharField(max_length=36)

class Foo(models.Model):
  bar = models.ForeignKey(Bar, null = True)

admin.py

class BarAdmin(admin.modelAdmin):
  ...

When I am editing the "Bar" class from the django admin, I would like to see every Foo objects in a multi-line select HTML tag. The relations between Foo and Bar should be updated when I validate the form.

How can I do this ?

Upvotes: 0

Views: 194

Answers (1)

kreld
kreld

Reputation: 752

You can address the Foo instances using

bar = Bar.objects.get(pk = bar_id)
foo_set = bar.foo_set.all()

where bar_id is the primary key of your Bar object, or alternatively

foo_set = Foo.objects.filter(bar__pk = bar_id) # Note the double underscore

If you want to render the Foo objects in a select tag in a template you could either do it manually:

<select>
{% for f in foo_set %}
<option value="{{ f.pk }}">{{ f }}</option>
{% endfor %}
</select>

Or you could create a django form, see django forms.

Upvotes: 1

Related Questions