Mayke Ferreira
Mayke Ferreira

Reputation: 174

Many to One Relation in Django With Existing Objects

I've started to study Django yesterday and I'm having some trouble with to creating a Many to One Relation based on objects I've previously created.

models.py

# -*- coding: utf-8 -*-
from django.db import models

class Item(models.Model):
    code = models.AutoField(primary_key=True)
    name = models.CharField(max_length=150, unique=True)
    
    class Meta:
        ordering = ('name', 'code')

    def __unicode__(self):
        return self.name


class Product(models.Model):
    code =  models.AutoField(primary_key=True)
    name = models.CharField(max_length=150, unique=True)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    photo = models.ImageField(null=True, blank=True, upload_to='/img/products')
    items = models.ForeignKey('Item')

    class Meta:
        ordering = ('name', 'code')

    def __unicode__(self):
        return self.name

admin.py

# -*- coding: utf-8 -*-
from django.contrib import admin
from Cadastro.models import Item, Product

class ItemAdmin(admin.ModelAdmin):
    model = Item
    list_display = ['code', 'name']
    list_filter = []
    search_fields = ['name', 'code']
    save_on_top = True


class ProductAdmin(admin.ModelAdmin):
    model = Product
    list_display = ['name', 'price']
    list_filter = []
    search_fields = ['name']
    save_on_top = True

admin.site.register(Item, ItemAdmin)
admin.site.register(Product, ProductAdmin)

Problem:

My problem is here:

items = models.ForeignKey('Item')

I want to create various Item objects, first.

After that, when I'll create the Products, I want to see a list of all my Items and select many items to be part of a Product.

Upvotes: 1

Views: 849

Answers (1)

Peter DeGlopper
Peter DeGlopper

Reputation: 37319

Your relationship is going the wrong way. If a Product can have multiple Items, make a ForeignKey from Item to Product. With the ForeignKey on Product, you're saying each product has exactly one Item, but each Item can belong to multiple Products.

The docs have more details and examples: https://docs.djangoproject.com/en/1.7/topics/db/examples/many_to_one/

Upvotes: 2

Related Questions