Imagine we have a model like that:
class Container(models.Model):
name = models.CharField(max_length=60)
class Element(models.Model):
container = models.ForeignKey(Container, blank=True, null=True)
Container
is the One, Element
is the many.
In Django admin, if I add a StackedInline
with model=Element
to the inlines
of the Container
model admin:
class Inline(admin.StackedInline):
model = Element
class ContainerAdmin(admin.ModelAdmin):
inlines = (Inline,)
admin.site.register(Container, ContainerAdmin)
I end up with a formset allowing me to enter new Element
objects on the Add Container form.
Instead, I would like to be given a select widget, to pick existing Element
objects.
Is that possible without introducing an extra model ?
To define a one to many relationship in Django models you use the ForeignKey data type on the model that has the many records (e.g. on the Item model).
str function in a django model returns a string that is exactly rendered as the display name of instances for that model.
A ManyToMany field is used when a model needs to reference multiple instances of another model. Use cases include: A user needs to assign multiple categories to a blog post. A user wants to add multiple blog posts to a publication.
I think you should be able to do it like this:
class ContainerAdminForm(forms.ModelForm):
class Meta:
model = Container
fields = ('name',)
element_set = forms.ModelMultipleChoiceField(queryset=Element.objects.all())
class ContainerAdmin(admin.ModelAdmin):
form = ContainerAdminForm
# register and whatnot
I don't know that I have anything like this in my project, but I'll let you know if I find something. You may also have to override the save()
method on the form in order to actually save the selected Element
s; I don't know if naming the field element_set
(or whatever the name of the reverse relation is) will be enough.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With