Sunday, April 29, 2012

Many-to-Many Intermediary Models in Django admin

Hello,

Here is the model I am working on :

class Recipe(models.Model):
title = models.CharField(max_length=200)
description = models.TextField(blank=True)
ingredient = models.ManyToManyField('Ingredient',
through='Content',null=True)

class Ingredient(models.Model):
name = models.CharField(max_length=200)

class Content(models.Model):
recipe = models.ForeignKey('Recipe')
ingredient = models.ForeignKey('Ingredient')
quantity = models.FloatField()

As you can see, I used a many-to-many relation to link an ingredient
to a recipe, and I did it through an intermediate model, Content, so I
can specify a quantity for the ingredient.

Here is my problem : In the Django admin I would like to be able to
add new Contents when I edit/create a Recipe.

So I did this in admin.py :

class ContentInline(admin.TabularInline):
model = Content
extra = 3

class RecipeAdmin(admin.ModelAdmin):
inlines = [ContentInline]

admin.site.register(Recipe, RecipeAdmin)

As expected, I can add new Contents but that does not allow me to
create a new Ingredient directly.
I could create new Ingredients independently and then create my
recipes but it is not convenient :/

Is there a way I can create an Ingredient along with a Content while I
edit my Recipe ?

Thank you for your answers ! Hope my question is clear enough...

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment