Django admin: how do I add an unrelated model field to a model change/add page?
I have the following models:
class Foo(models.Model):
field1 = models.IntegerField()
...
class Bar(models.Model):
field1 = models.IntegerField()
...
class Foo_bar(models.Model):
foo = models.ForeignKey(Foo)
bar = models.ForeignKey(Bar)
...
In the admin, I want it so that in the Foo change/add page, you can specify a Bar object, and on save I开发者_运维技巧 want to create a Foo_bar object to represent the relationship. How can I do this through customizing the Admin site/ModelAdmins? Note that inlining isn't quite what I need because there is no explicit foreign key relationship between foo and bar. And second, I don't actually want to edit bar objects, I just want to choose from amongst the ones that are in the system.
Thanks.
Are you sure you don't just want a ManyToManyField? In the admin, this would manifest as a multiple-selection list of Bar
objects. Look at the group selection part of the admin for User
.
If you need additional data attached to the relationship, you could use a through
parameter:
class Foo(models.Model):
field1 = models.IntegerField()
bars = models.ManyToManyField("Bar", related_name="foos", through="Foo_bar")
You'll need to add Foo_bar to the admin in order to edit these additional parameters in the admin.
I can think of two possibilities:
You could create a custom form for your
Foo
model and add a field containing theBar.objects.all()
queryset to it. then override the ModelAdmin's defaultsave_form()
method to create a newBar
instance upon saving the object.You could create a custom Field class and add it to you
Foo
model, and class this functionality via a ´post_save` signal...
For those actually looking to add an unrelated model field to add/change, use ModelChoiceField
from django import forms
class CustomForm(forms.Form):
foo = forms.ModelChoiceField(queryset=Foo.objects.all())
bar = forms.ModelChoiceField(queryset=Bar.objects.all())
Then simply add the form to the ModelAdmin's add_form/change_form
精彩评论