我有一个名为billing
的应用。以下是我的应用中的模型。
class ProductType(models.Model):
name = models.CharField(max_length=128)
unique_id = models.CharField(max_length=128)
price = models.DecimalField(max_digits=50,decimal_places=4)
class Product(models.Model):
type = models.ForeignKey(ProductType,related_name="products")
mac_id = models.CharField(max_length=128)
product_unique_id = models.CharField(max_length=128)
assigned = models.BooleanField(default=False)
class BillRecord(models.Model):
products = models.ManyToManyField(Product, related_name="billrecords",blank=True)
send_sms = models.BooleanField(default=True)
send_email = models.BooleanField(default=True)
invoice = models.FileField(null=True,blank=True,upload_to='invoices/')
def save(self, *args, **kwargs):
super(BillRecord, self).save(*args, **kwargs)
total_products = Product.objects.filter(assigned=False)
self.products.add(*total_products)
保存BillRecord
对象并查询对象products
后返回billing.Product.None
如何在products
模型的保存方法中添加BillRecord
。
答案 0 :(得分:1)
您需要更改保存方法
def save(self, *args, **kwargs):
item = super(BillRecord, self).save(*args, **kwargs)
total_products = Products.objects.filter(assigned=False)
item.products.add(*total_products)
item.save()
首先,调用super()。save方法,然后添加要与自身对象关联的对象。
答案 1 :(得分:0)
管理员中的多对多保存将无法正常工作。您需要像这样覆盖Admin类....
class BillRecordAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
super(ArticleAdmin, self).save_model(request, obj, form, change)
total_products = Product.objects.filter(assigned=False)
form.instance.products.add(*total_products)
admin.site.register(BillRecord, BillRecordAdmin)
答案 2 :(得分:0)
您正在尝试向billrecord对象添加多对多字段对象,这就是您收到错误的原因,“
"<BillRecord: test>" needs to have a value for field "billrecord" before this many-to-many relationship can be used"
首先,您需要保存BillRecord模型的对象,然后将该对象的查询集添加到多对多关系中。