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

时间:2014-09-26 15:33:41

标签: python django

How to create an object for a Django model with a many to many field?

从上面的问题我知道我们以后可以保存很多到很多字段。

models.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)

views.py

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' object has no attribute 'store'

我也试过add现在正在工作。 所以问题是如何保存()

5 个答案:

答案 0 :(得分:0)

new.stores.all()

返回链接到该对象的所有商店。

答案 1 :(得分:0)

也许:

  1. 将Foo改为曲目
  2. Tracks.objects.filter(id = x)to Tracks.objects.get(id = x)
  3. 让我知道它是怎么回事

答案 2 :(得分:0)

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

...
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)

答案 3 :(得分:0)

为什么这么混乱......你在那里得到了id,就像

那样叫商店
new_track.save()
new_track.store.add(request.POST['store'])

答案 4 :(得分:0)

从2020年开始,这是我将ManyToMany Field保存到给定对象的方法。

简短回答

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']

views.py on POST

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'),
]

我希望这会有所帮助。问候