Skip to content

Instantly share code, notes, and snippets.

@mcabrams
Last active April 4, 2019 00:42
Show Gist options
  • Save mcabrams/cb4fa75bbfa2b200070b0769012bd140 to your computer and use it in GitHub Desktop.
Save mcabrams/cb4fa75bbfa2b200070b0769012bd140 to your computer and use it in GitHub Desktop.
Factory boy - related factory retrieval
# Models
class Foo(Model):
text = models.CharField(max_length=64, blank=False)
class Bar(Model):
text = models.CharField(max_length=64, blank=False)
# Factories
class FooFactory(factory.django.DjangoModelFactory):
class Meta:
model = Foo
text = factory.Faker('pystr')
class BarFactory(factory.django.DjangoModelFactory):
class Meta:
model = Bar
text = factory.Faker('pystr')
class FooWithBarFactory(FooFactory):
bar = factory.RelatedFactory(BarFactory, text=factory.SelfAttribute('..text'))
# How I might retrieve related factory now:
foo = FooWithBarFactory()
bar = Bar.objects.get(text=foo.text)
# How I'd like to retrieve related factory - Obviously doesn't work as things stand
foo, bar = FooWithBarFactory()
# or ?
foo.bar = FooWithBarFactory()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment