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.