Django 1.2.1 Inline Admin for Many To Many Fields

后端 未结 2 903
花落未央
花落未央 2021-02-07 18:04

I recently upgraded to Django 1.2.1 because I was specifically interested in the ability to have basic many-to-many inline fields. When using the admin like so:

Initial

2条回答
  •  名媛妹妹
    2021-02-07 18:42

    Do one of these examples accomplish what you are trying to do?

    a:

    # Models:
    
    class Ingredient(models.Model):
        name = models.CharField(max_length=128)
    
    class Recipe(models.Model):
        name = models.CharField(max_length=128)
        ingredients = models.ManyToManyField(Ingredient, through='RecipeIngredient')
    
    class RecipeIngredient(models.Model):
        recipe = models.ForeignKey(Recipe)
        ingredient = models.ForeignKey(Ingredient)
        amount = models.CharField(max_length=128)
    
    
    # Admin:
    
    class RecipeIngredientInline(admin.TabularInline):
        model = Recipe.ingredients.through
    
    class RecipeAdmin(admin.ModelAdmin):
        inlines = [RecipeIngredientInline,]
    
    class IngredientAdmin(admin.ModelAdmin):
        pass
    
    admin.site.register(Recipe,RecipeAdmin)
    admin.site.register(Ingredient, IngredientAdmin)
    

    b:

    # Models:
    
    class Recipe(models.Model):
        name = models.CharField(max_length=128)
    
    class Ingredient(models.Model):
        name = models.CharField(max_length=128)
        recipe = models.ForeignKey(Recipe)
    
    
    # Admin:
    
    class IngredientInline(admin.TabularInline):
        model = Ingredient
    
    class RecipeAdmin(admin.ModelAdmin):
        inlines = [IngredientInline,]
    
    admin.site.register(Recipe,RecipeAdmin)
    

提交回复
热议问题