【问题标题】:why i am getting Direct assignment to the forward side of a many-to-many set is prohibited.?为什么我禁止直接分配到多对多集合的前端。?
【发布时间】:2021-08-18 14:32:20
【问题描述】:

当我尝试在 auction_watching 模型上添加数据时出现此错误。我尝试与 auction_watchingproducts 表建立多对多关系。但是为什么我会收到这个错误。请帮帮我

models.py

from django.db import models
from PIL import Image
from datetime import datetime, timedelta
from django.contrib.auth.models import User
# Create your models here.
class Products(models.Model):
    product_img = models.ImageField(upload_to='pics')
    product_title = models.CharField(max_length=100)
    price = models.IntegerField()
    deadline = models.DateTimeField()
    def save(self, *args, **kwargs):
        super(Products, self).save(*args, **kwargs)
        img=Image.open(self.product_img.path)
        if img.height >= 300 and img.width >=300:
            img = img.resize((200, 300)) # resize use to resize image, don't care about ration
            # output_size = (200,300)
            # img.thumbnail(output_size) # thumbnail use to resize image with aspect ration
            img.save(self.product_img.path)
class Auction_Watching(models.Model):
    product_info = models.ManyToManyField(Products, null=True )
    User_id = models.IntegerField()
    current_bid = models.IntegerField(null=True)
    action_status = models.BooleanField(default='True')
    def __str__(self):
        return self.name

views.py

def auction_watch(request,pk):
    username=request.session['username']
    user_id= request.session['value']
    product_information = Products.objects.get(id=pk)
    product_watch = Auction_Watching.objects.create(product_info=product_information, User_id=user_id)
    return render(request, 'auctionApp/auction_watch.html')

【问题讨论】:

    标签: django django-models django-rest-framework django-views django-database


    【解决方案1】:

    在做了一些研究之后,我得到了自己问题的答案。 在 django 中,我们不能直接在 ManyToMany 字段中赋值,例如:
    product_watch = Auction_Watching.objects.create(product_info=product_information, User_id=user_id)

    这里是 ManyToMany 字段中的 project_info,我直接插入了 django 不允许的值。相反,我们需要这样做:首先我们需要在一个变量中获取该表的所有值:
    product_description = Products.objects.get(id=pk) 然后在没有此 ManyToMany 字段的表中创建值,例如:product_watch = Auction_Watching.objects.create(User_id=user_id)。然后在下一行添加 ManyToMany 字段,例如:product_watch.product_info.add(product_description),您不需要使用 save()。

    【讨论】:

      猜你喜欢
      • 2019-03-02
      • 1970-01-01
      • 2021-07-01
      • 2018-10-05
      • 2020-03-21
      • 2020-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多