在管理中保存时Django ManyToManyField错误?

2024-05-19 01:48:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码怎么了?在

class Group(ImageModel):
     title = models.CharField(verbose_name = "Title", max_length=7)
     photos = models.ManyToManyField('Photo', related_name='+', 
                                             verbose_name=_('Photo'),
                                             null=True, blank=True)

    .....


     pid = Photo.objects.get(image = str_path)

     gid= Group.objects.get(id = self.id)       

     self.save_photos(gid, pid)

    ....


    def save_photos(self, gid, pid):
       group_photo = GroupPhotos(groupupload=gid.id,
                                        photo=pid.id
                                        )
       group_photo.save()

我的群像模型是:

^{pr2}$

当我想从管理面板中保存它时,我得到如下值错误:

Cannot assign "38": "GroupPhotos.groupupload" must be a "Group" instance.

有了group_photo = GroupPhotos(groupupload=gid, photo=pid)定义,它可以工作,但是GroupPhotos表(GroupPhotos)中没有任何更改。打印这个print pid.id,' >>> ',gid.id我得到了真实的关系。。。在

更新:

我从早上就开始工作了,但是没有进展。。。我也试过了,但没有改变:

pid = Photo.objects.get(image = str_path)

ger = Group.objects.get(id = self.id)
        ger.title = self.title       
        ger.save()

        ger.photos.add(pid)

Tags: nameselfidgetobjectstitlesavegroup
2条回答

错误在这里:

group_photo = GroupPhotos(groupupload=gid.id, photo=pid.id)

groupupload和{}的参数应该分别是Group和{}的实例。尝试以下操作:

^{pr2}$

换句话说,创建对象时,需要传递预期类型的参数,而不是整数(它可能是所需对象的主键,但也可能不是,这就是为什么需要传递正确类型的对象的原因)。在

我通过在我的多个字段中添加选项解决了我的问题:

photos = models.ManyToManyField('Photo', related_name='+', 
                                     verbose_name=_('Photo'),
                                     null=True, blank=True, through=GroupPhotos)

一些关于很多很多场。通过here

Django will automatically generate a table to manage many-to-many relationships. However, if you want to manually specify the intermediary table, you can use the through option to specify the Django model that represents the intermediate table that you want to use.

The most common use for this option is when you want to associate extra data with a many-to-many relationship.

相关问题 更多 >

    热门问题