我有3种型号,如下所示:
class Service(models.Model):
name = models.CharField(max_length=50, unique=True)
class ServiceGroup(models.Model):
name = models.CharField(max_length=50, unique=True)
services = models.ManyToManyField(Service, through=ServiceToServiceGroup)
class ServiceToServiceGroup(models.Model):
service = models.ForeignKey(Service)
service_group = models.ForeignKey(ServiceGroup)
我有一个需要作为ServiceGroup实例的M2M关联进行的服务列表。我尝试了以下方法:
In [145]: instance = ServiceGroup.objects.get(pk=1)
In [146]: instance.services.all()
Out[146]: <QuerySet [<Service: service-1>]>
In [147]: new = ['service-2']
In [148]: service_objects = Service.objects.filter(name__in=new)
In [149]: service_objects
Out[149]: <QuerySet [<Service: service-2>]>
In [150]: instance.service_set = service_objects
In [151]: instance.save()
In [152]: instance.services.all()
Out[152]: <QuerySet [<Service: service-1>]>
但是,很明显,这没有用。正确的方法是什么?
答案 0 :(得分:1)
要创建连接,您需要创建一个调解器实例:
for service in service_objects:
ServiceToServiceGroup.objects.create(
service=service,
service_group=instance,
)
您还可以使用批量创建:
ServiceToServiceGroup.objects.bulk_create(
[ServiceToServiceGroup(
service=service,
service_group=instance
) for service in service_objects]
)
要删除旧关系,可以运行:
ServiceToServiceGroup.objects.filter(service_group=instance).delete()
或
instance.servicetoservicegroup_set.all().delete()
在运行添加脚本之前。