Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在django中保存多对多关系_Python_Django - Fatal编程技术网

Python 如何在django中保存多对多关系

Python 如何在django中保存多对多关系,python,django,Python,Django,从上面的问题,我知道我们可以节省多对多领域只有以后 型号.py class Store(models.Model): name = models.CharField(max_length=100) class Foo(models.Model): file = models.FileField(upload_to='') store = models.ManyToManyField(Store, null=True, blank=True) new_track.file =

从上面的问题,我知道我们可以节省多对多领域只有以后

型号.py

class Store(models.Model):
   name = models.CharField(max_length=100)

class Foo(models.Model):
   file = models.FileField(upload_to='')
   store = models.ManyToManyField(Store, null=True, blank=True)
new_track.file = request.FILES['file']
new_track.save()
视图.py

class Store(models.Model):
   name = models.CharField(max_length=100)

class Foo(models.Model):
   file = models.FileField(upload_to='')
   store = models.ManyToManyField(Store, null=True, blank=True)
new_track.file = request.FILES['file']
new_track.save()
和文件上传工作良好,然后稍后我修改我的代码添加存储,然后我在这里

现在我确定db返回id在这里。然后我尝试了下面的代码,但这只给了我一个错误

    x = new_track.id
    new = Foo.objects.filter(id=x)
    new.store.id = request.POST['store']
    new.save()
好的,这里的错误是,
“QuerySet”对象没有属性“store”

我还尝试了
add
,现在也可以了。 所以问题是如何保存()

返回链接到对象的所有存储。

可能:

  • 将Foo更改为Tracks
  • Tracks.objects.filter(id=x)到Tracks.objects.get(id=x)

  • 让我知道它是如何进行的

    保存具有许多关系的对象的正确方法是:

    ...
    new_track.file = request.FILES['file']
    new_track.save()
    
    new_store = Store.objects.get(id=int(request.POST['store']))
    new_track.store.add(new_store)
    

    为什么会如此困惑。。如果你在那里拿到了身份证,打电话给商店

    new_track.save()
    new_track.store.add(request.POST['store'])
    

    到2020年,我的方法是将许多字段保存到给定对象

    简短回答

    class HostingRequestView(View):
        def post(self, request, *args, **kwargs):
            form = VideoGameForm(request.POST)
            if form.is_valid():
                obj = form.save(commit=False)
                obj.updated_by = request.user
                obj.save()
    
                selected_categories = form.cleaned_data.get('category') #returns list of all selected categories e.g. ['Sports','Adventure']
                #Now saving the ManyToManyField, can only work after saving the form
                for title in selected_categories:
                    category_obj = Category.objects.get(title=title) #get object by title i.e I declared unique for title under Category model
                    obj.category.add(category_obj) #now add each category object to the saved form object
                return redirect('confirmation', id=obj.pk)
    
    完整答案

    class HostingRequestView(View):
        def post(self, request, *args, **kwargs):
            form = VideoGameForm(request.POST)
            if form.is_valid():
                obj = form.save(commit=False)
                obj.updated_by = request.user
                obj.save()
    
                selected_categories = form.cleaned_data.get('category') #returns list of all selected categories e.g. ['Sports','Adventure']
                #Now saving the ManyToManyField, can only work after saving the form
                for title in selected_categories:
                    category_obj = Category.objects.get(title=title) #get object by title i.e I declared unique for title under Category model
                    obj.category.add(category_obj) #now add each category object to the saved form object
                return redirect('confirmation', id=obj.pk)
    
    models.py

    class Category(models.Model):
        title = models.CharField(max_length=100, null=True, unique=True)
    
    class VideoGame(models.Model):
        game_id = models.AutoField(primary_key=True)
        name = models.CharField(max_length=50, blank=False, null=False)
        updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=False, on_delete=models.CASCADE)
        category = models.ManyToManyField(Category) #ManyToMany Category field
        date_added = models.DateTimeField(auto_now_add=True, verbose_name="date added")
    
    forms.py ModelForm

    class VideoGameForm(forms.ModelForm):
        CATEGORIES = (
            ('Detective', 'Detective'),
            ('Sports', 'Sports'),
            ('Action', 'Action'),
            ('Adventure', 'Adventure'),
        )
    
        category = forms.MultipleChoiceField(choices=CATEGORIES, widget=forms.SelectMultiple())
    
        class Meta:
            model = VideoGame
            fields = ['name', 'category', 'date_added']
    
    POST上的views.py

    class HostingRequestView(View):
        def post(self, request, *args, **kwargs):
            form = VideoGameForm(request.POST)
            if form.is_valid():
                obj = form.save(commit=False)
                obj.updated_by = request.user
                obj.save()
    
                selected_categories = form.cleaned_data.get('category') #returns list of all selected categories e.g. ['Sports','Adventure']
                #Now saving the ManyToManyField, can only work after saving the form
                for title in selected_categories:
                    category_obj = Category.objects.get(title=title) #get object by title i.e I declared unique for title under Category model
                    obj.category.add(category_obj) #now add each category object to the saved form object
                return redirect('confirmation', id=obj.pk)
    
    重定向的URL路径

    urlpatterns = [
        path('confirmation/<int:id>/', Confirmation.as_view(), name='confirmation'),
    ]
    
    urlpatterns=[
    路径('confirmation/',confirmation.as_view(),name='confirmation'),
    ]
    

    我希望这能有所帮助。注意

    尝试将代码更改为new.store=request.POST['store']
    。filter
    返回查询集。要获取对象,您需要一个
    .get()
    .filter()[0]
    @karthikr我敢肯定在保存时会获取id值。我的方法是保存多对多关系的正确方法吗?如果我按我的方式做,我得到的
    Foo'对象没有属性“name”
    我也尝试了你的。并且doniyor告诉不同的方法返回存储对象,然后使用add方法保存。什么是正确的方法?请help@cdvv7788我更改了我的问题,请仔细研究。我认为这与问题无关。他收到的错误与存储有关,应该作为stores.filter或任何模型对象进行查询。我尝试了你的问题,得到的错误类似于
    nvalid literal for int()以10为基数:“on”
    @em_uuuuuulife试试这个
    new_ustore=store.objects.get(id=int(request.POST['store']))
    ok。。现在没有错误。我想这是一个节约的目标。然后我访问了mysql工作台,表'dsp\u foo\u store',有三个字段(id,foo\u id,store\u id)。如果foo_id为9,则对应的store_id为3,但我选择了multiple,表示有三个以上的复选框,但它只返回一个对象。为什么?@em\uuuuu life(别忘了投票并检查答案,如果它解决了你的第一个问题)。我不明白你所说的
    “我选择多个表示多于三个复选框”
    。你能再描述一下这个例子吗?我有疑问,比如
    对象。get
    只返回一个对象,但
    请求。POST['store']
    返回多个值bcse每个复选框呈现的存储
    ids
    …我更改了我的问题,请注意it@em___life检查我的第二个建议。过滤器返回一个结果列表(您可以像这样查看查询集),您需要一个对象。通过获取或尝试过滤器更改过滤器()[0]谢谢,现在选择字段正在保存,但我有多项选择条目,然后mysql给我此错误
    (1062,“关键“轨迹id”的重复条目“4-5”)
    请求。POST['store']
    只是一个字符串,您不能
    。添加()
    许多相关对象