MZA
MZA

Reputation: 1057

Django Factory Boy - Reverse dependencies (reverse ForeignKey) common recipy

I am new to FactoryBoy. I am trying the example for the exact example in the docs: reverse dependencies .

1) Is it correct that the "UserLogFactory" mentioned is "so obvious" one should make it oneself as in:

class UserLogFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.UserLog

2) I am getting an AttributeError:

type object 'UserLog' has no attribute 'ACTION_CREATE'

I searched the internet, I found 1 reference (github error report) who seemed to have solved it himself the same day. He did not mention the solution, but from his comments, I gather it is something obvious...

Thanks in advance for the help!
Kind regards.

Upvotes: 5

Views: 1948

Answers (2)

twihoX
twihoX

Reputation: 189

If you look at the example, the models.UserLog.ACTION_CREATE is actually an attribute (value of it to be precise) of the UserLog model. I.e. it is irrelevant to the task at hand. Therefore you can just drop it.

It is the same as if the UserLog model had a created_at field, or any other field. They just show you that you are able to specify values of the related factory itself.

Upvotes: 0

Oleksii M
Oleksii M

Reputation: 1518

As per factory-boy docs regarding RelatedFactory and SubFactory, named parameters you define in RelatedFactory creation will be passed to UserLogFactory, so that action is expected to be field in UserLogFactory.

log = factory.RelatedFactory(UserLogFactory, 'user', action=models.UserLog.ACTION_CREATE)

AttributeError occurs because UserLog lack the constant definition for ACTION_CREATE, which I assume is one of possible choices for UserLog.action field.

This is possible way to define UserLog model:

class UserLog(models.Model):
    ACTION_CREATE = 'CREATE'
    ACTION_UPDATE = 'UPDATE'

    ACTION_CHOICES = (
        (ACTION_CREATE, 'create'),
        (ACTION_UPDATE, 'update'),
    )
    user = models.ForeignKey(User)
    action = models.CharField(choices=ACTION_CHOICES)

For more information on choices take a look at Django choices docs

Upvotes: 5

Related Questions