How to validate and create related objects together with forms

和自甴很熟 提交于 2019-12-10 22:14:51

问题


I am trying to validate a related object (ForeignKey) when creating an object the base object with forms. The related object may or may not exist. Below I use MPTT but this is a general foreign key problem.

I have a model like this:

# model:
class MyMPTTModel(models.Model):
    name = models.CharField(max_length=256, unique=True) # this is set
    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') 

#form
class MyMPTTModelForm(forms.ModelForm):

    parent = mptt_forms.TreeNodeChoiceField(queryset=MyMPTTModel.objects.all())

    class Meta:
        model = MyMPTTModel
        fields = ['name', 'parent']

I want to atomically get_or_create a set of nodes with the form(set?).

Something like:

paths = ['each-part/of-the-path/is-the-name', 'each-part/of-the-path/could-have-mutliple-children']
for path in paths:
    parent = None
    nodes = []
    for p in path.split('/'):    
        nodes.append({'name': p, 'parent': parent })
        parent = p

    for node in nodes:
        name, parent = node.values()
        if parent:
            parent = MyMPTTModel.objects.get_or_create(name=parent)[0]
        MyMPTTModel.objects.get_or_create(name=name)

I'm struggling with the get_or_create part of the form as the parent may not exist and therefore is not a valid choice. I could create the parents before I create the next node, but then when it fails, it would create a bunch of orphan nodes since the children failed.

I want to validate each node and create them all together (or not).

来源:https://stackoverflow.com/questions/50972039/how-to-validate-and-create-related-objects-together-with-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!