gpt4 book ai didi

django - 如何为 manytomanyfield 设置默认值

转载 作者:行者123 更新时间:2023-12-02 00:22:29 25 4
gpt4 key购买 nike

是否有解决“实例需要有主键值才能使用多对多关系”错误的方法?

我有一个包含多个字段的模型,包括与另一个模型的多对多关系。当我创建模型的新实例时,我有一个函数可以在这些字段上设置默认值。我在处理 HTTP GET 时在 View 中执行此操作。 m2m 字段使用表单集呈现。

下面是一些描述情况的伪代码:

class MyRelatedModel(models.Model):
name = models.CharField(max_length=100,blank=True)

class MyModel(models.Model):
name = models.CharField(max_length=100,blank=True)
relatedModels = models.ManyToManyField("MyRelatedModel")

def initialize(self):
self.name = "my default name"
# this bit doesn't really matter...
# just assume I am creating a new set of RelatedModels that I want to associate with my this new MyModel...
newRelatedModels = []
for name in ["related model 1", "related model 2", "related model 3"]:
relatedModel = MyRelatedModel(name=name)
relatedModel.save()
newRelatedModels.append(relatedModel.id)
self.relatedModels = newRelatedModels # this is invalid!

def MyView(request):
if request.method == 'GET':
model = MyModel()
model.initialize()
form = MyForm(instance=model)
return render_to_response("my_template.html", {"form" : form}, context_instance=RequestContext(request))

有什么建议吗?

我怀疑我可能需要在表单端而不是模型端处理这个问题,但这也让我感到困惑。

最佳答案

对于 1.3.1 中对我有用的表单:

是类似这个的,inital中的manytomany

使用硬编码 ID:

def MyView(request):
if request.method == 'GET':
model = MyModel( name = "my default name")
initial = { 'relatedModels': [1,] } # assuming you knew the id and wanted to hardcode it
form = MyForm( instance=model, initial=initial )
return render_to_response("my_template.html", {"form" : form}, context_instance=RequestContext(request))

使用查询按名称填充:

def MyView(request):
if request.method == 'GET':
model = MyModel( name = "my default name")
initial = { 'relatedModels': [ o.pk for o in list(MyRelatedModel.objects.filter( name__in=("related model 1", "related model 2", "related model 3")))], }
form = MyForm( instance=model, initial=initial )
return render_to_response("my_template.html", {"form" : form}, context_instance=RequestContext(request))

关于django - 如何为 manytomanyfield 设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10261671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com