Jeremy Weirich
Jeremy Weirich

Reputation: 387

Django - Adding multiple children to a model

I have a Test class that will contain an unknown number of WriteData and VerifyData objects:

class Test(models.Model):
    objective = models.ForeignKey(Objective)
    test_at = models.CharField(max_length=NAME_MAX_LENGTH, unique=True)
    description = models.CharField(max_length=DESCRIPTION_MAX_LENGTH, default="")


class WriteData(models.Model):
    test = models.ForeignKey(Test)
    write_variable = models.CharField(max_length=NAME_MAX_LENGTH, default="")
    write_value = models.CharField(max_length=NAME_MAX_LENGTH, default="")


class VerifyData(models.Model):
    test = models.ForeignKey(Test)
    verify_variable = models.CharField(max_length=NAME_MAX_LENGTH, default="")
    relational_operator = models.CharField(max_length=NAME_MAX_LENGTH, default="")
    verify_value = models.CharField(max_length=NAME_MAX_LENGTH, default="")
    verify_tolerance = models.CharField(max_length=NAME_MAX_LENGTH, default="")

I get the following error when I try to populate my database: django.core.exceptions.FieldError: Cannot resolve keyword 'verify_variable' into field. Choices are: id, test, test_id, write_value, write_variable

I suspect this is because test has only one relation, which is to write_data. Is the solution to use a many-to-many relationship? Many-to-many feels wrong, because each of these write_data/verify_data are unique and will only go in one test. How do I resolve this?

I took a look at: Can a single model object be a parent of multiple child objects?, but this is a different situation - I'd like to add relations between these classes, not subclass from them.

Here is a pastebin link to the population script.

Upvotes: 0

Views: 400

Answers (1)

Siegmeyer
Siegmeyer

Reputation: 4512

In you script you have a method add_verify_data (line 148):

def add_verify_data(test, v_var, rel_op, v_val, v_tol):
    vd = WriteData.objects.get_or_create(
        test=test,
        verify_variable=v_var,
        relational_operator=rel_op,
        verify_value=v_val,
        verify_tolerance=v_tol,
    )[0]
    vd.save()
    return vd

which seems to be creating instance of WriteData model with verify_variable, relational_operator, verify_value and verify_tolerance but this model doesn't have those fields, only: write_variable and write_value.

Upvotes: 1

Related Questions