简体   繁体   English

在创建不同的 model 对象时,如何选择性地指定 django model 字段值?

[英]How to selectively specify a django model field value when creating different model objects?

I have the following models in my django app:我的 django 应用程序中有以下型号:

from django.db import models

class TaskTracking(models.Model):
    name = models.CharField(max_length=20)

class Parent(models.Model):
    my_attribute = models.CharField(max_length=255, blank=True)
    my_attribute2 = models.CharField(max_length=255, blank=True)


class Child(Parent):
    tracking = models.ForeignKey(TaskTracking, on_delete=models.PROTECT)

Then I have another file where I am trying to make instances of these two models.然后我有另一个文件,我试图在其中创建这两个模型的实例。 What I intend to do is invoke the create method, based on a parameter, something like this:我打算做的是根据参数调用 create 方法,如下所示:

from .models import *

class BaseObjectCreator:
    model = Parent
    def createModelObject(trackingEnabled=False):
        tracking_instance = None

        if trackingEnabled:
             tracking_instance = TaskTracking.objects.create(name='Dummy name')

        instance = self.model.objects.create(
                   my_attribute = 'value1',
                   my_attribute = 'value2',
                   tracking = tracking_instance if trackingEnabled
                   )

class ChildObjectCreator:
    model = Child
    def createModelObject(trackingEnabled=True):
        super().createModelObject(trackingEnabled)

But this is not working and throwing error for this line tracking = tracking_instance if trackingEnabled .但这不起作用,并且这条线tracking = tracking_instance if trackingEnabled抛出错误。 I need something like this for refactoring a large code which involves models like the ones defined above.我需要这样的东西来重构涉及上面定义的模型的大型代码。 Can you suggest the correct strategy?你能提出正确的策略吗?

PS - The tracking attribute of the Child model is an FK hence NOT NULL constraint is implied. PS - Child model 的跟踪属性是一个 FK,因此暗示了 NOT NULL 约束。

There's another strategy to tackle this.还有另一种策略来解决这个问题。 You could go about it in this manner:你可以用这种方式 go 关于它:

from .models import *

class BaseObjectCreator:
    model = Parent
    def createModelObject(trackingEnabled=False):
        instance = self.model.objects.create(
                   my_attribute = 'value1',
                   my_attribute = 'value2',
                   )
        if (trackingEnabled):
            instance.tracking = 'value3'
            instance.save()

class ChildObjectCreator:
    model = Child
    def createModelObject(trackingEnabled=True):
        super().createModelObject(trackingEnabled)

I am not aware if there's a way to invoke conditional statements inline.我不知道是否有办法内联调用条件语句。 But this seems like a clean enough solution.但这似乎是一个足够干净的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM