Django与现有对象的多对一关系 [英] Many to One Relation in Django With Existing Objects
问题描述
我昨天开始学习Django,但在基于先前创建的对象创建一对多关系时遇到了一些麻烦.
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.
# -*- 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')
首先,我想创建各种 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.
推荐答案
您的关系正走错路.如果Product
可以具有多个Item
,则将ForeignKey
从Item
更改为Product
.在Product
上使用ForeignKey
时,您要说的是每个产品只有一个Item
,但是每个Item
可以属于多个Product
.
Your relationship is going the wrong way. If a Product
can have multiple Item
s, 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 Product
s.
文档具有更多详细信息和示例: https://docs.djangoproject.com/en/1.7/topics/db/examples/many_to_one/
The docs have more details and examples: https://docs.djangoproject.com/en/1.7/topics/db/examples/many_to_one/
这篇关于Django与现有对象的多对一关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!