尝试使用内联来获取多个对象

时间:2013-08-05 16:01:39

标签: python django

我正在尝试获得可以无限次添加的PurchaseOrder。也许这比我想的要容易,但这就是我想象中的问题:

我希望在不添加另一个VendorProfile的地方,它会添加另一个PurchaseOrder。我的最终目标是能够从同一个添加屏幕添加1,2,20等PurchaseOrder。无法添加PurchaseOrder,然后添加VendorProfile。 这是一些代码:在models.py

class PurchaseOrder(models.Model):
   product = models.CharField(max_length=256)
   dollar_amount = models.FloatField()
   item_number = models.AutoField(primary_key=True)
   vendor = models.ForeignKey('VendorProfile')

class VendorProfile(models.Model):
   name = models.CharField(max_length=256)
   address = models.CharField(max_length=512)
   city = models.CharField(max_length=256)

在admin.py

class ProductInline(admin.StackedInline):
   model = VendorProfile 
   extra = 3


class PurchaseOrderAdmin(admin.ModelAdmin):
   #...
   inlines = [ProductInline]

1 个答案:

答案 0 :(得分:2)

如果我理解正确,你就会将许多PurchaseOrder与一个VerndorProfile联系起来。在这种情况下,最好使用ManyToManyField 例如:

models.py:

class PurchaseOrder(models.Model):
    product = models.CharField(max_length=256)
    dollar_amount = models.FloatField()
    item_number = models.AutoField(primary_key=True)

    def __unicode__(self):
        return u'{} {}'.format(self.product, self.dollar_amount)


class VendorProfile(models.Model):
    name = models.CharField(max_length=256)
    address = models.CharField(max_length=512)
    city = models.CharField(max_length=256)
    purchased_orders = models.ManyToManyField('PurchaseOrder')

admin.py

class VendorProfileAdmin(admin.ModelAdmin):
    filter_horizontal = ('purchased_orders', )
admin.site.register(VendorProfile, VendorProfileAdmin)

enter image description here