Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Django admin, in a Many-to-One relationship, show a select list to pick EXISTING "Many" from the "One"

Tags:

django

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 ?

like image 236
Ad N Avatar asked Aug 07 '15 15:08

Ad N


People also ask

How does Django define many to one relationships?

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).

What is __ str __ In Django model?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model.

What is many to many field in Django?

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.


1 Answers

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 Elements; I don't know if naming the field element_set (or whatever the name of the reverse relation is) will be enough.

like image 157
Alex Van Liew Avatar answered Oct 14 '22 00:10

Alex Van Liew