factory_boy
factory_boy copied to clipboard
build strategy is not working with reverse relations
Description
We have interesting use case recently, and that is, to render a PDF preview without hitting the db. We realized that we could use the build strategy which creates instances, but not saving them in db.
Model / Factory code
# models.py
class Order:
...
class Ticket:
ticket = models.ForeignKey(Order, related_name='tickets')
# factories.py
class OrderFactory:
@factory.post_generation
def tickets(self, create, extracted, **kwargs):
TicketFactory.build(order=self)
print(self.tickets.all()) # returns []
class TicketFactory:
...
Observed behaviors:
order = OrderFactory.build()
ticket = TicketFactory.build(order=order)
print(ticket.order) # works ok
print(order.tickets.all()) # returns []
print(ticket.order.tickets.all()) # returns []
ticket = TicketFactory.build()
print(ticket.order) # works ok
print(ticket.order.tickets.all()) # returns []
Expected behavior:
-
order.ticketsshould be non-empty.
Is it working as intended? Is there a workaround so that the reverse relations will be linked properly? Removing the post_generation hook has no effect also. And they work as intended when using the default create strategy, so issue is only in build strategy. Thanks a lot.