title: How to properly associate FactoryBoy subfactory with child object
body: <p>I have some tests that were working when I ran them with regular database objects but are broken now that I am using FactoryBoy factories.  I think I understand why they are broken but am struggling with the correct way to set this up.</p>
  
  <p>Here are my factories:</p>
  
  <pre><code>@register
  class UserFactory(BaseFactory):
      """User factory."""
  
      username = Sequence(lambda n: 'user{0}'.format(n))
      email = Sequence(lambda n: 'user{0}@example.com'.format(n))
      password = PostGenerationMethodCall('set_password', 'example')
      active = True
  
      class Meta:
          """Factory configuration."""
  
          model = User
  
  @register
  class ExperimentFactory(BaseFactory):
      """Experiment Factory."""
  
      date = fake.date_this_decade(before_today=True, after_today=False)
      scanner = Iterator(['GE', 'Sie', 'Phi'])
  
      class Meta:
          """Factory configuration."""
          model = Experiment
  
      user = factory.SubFactory(UserFactory)
  </code></pre>
  
  <p>According to <a href="https://stackoverflow.com/a/33484240/2066083">this answer</a> and other examples, FactoryBoy is supposed to be handling the foreign key assignment behind the scenes.</p>
  
  <p>But when I try to initialize my ExperimentFactory object in my fixture, I have a problem.  </p>
  
  <pre><code>@pytest.fixture(scope='function')
  @pytest.mark.usefixtures('db')
  def mocked_scan_service(db, mocker, request):
      user = UserFactory(password='myprecious')
      db.session.add(user)
      num_exp, num_scans, exp_id, scan_id, exp_uri, scan_uri = request.param
  
      for i in range(num_exp):
          experiment = ExperimentFactory(user_id = user.id)
          db.session.add(experiment)
  
      db.session.commit()
  
      ss = ScanService(user.id, experiment.id)
      for i in range(num_scans):
          ss._add_scan_to_database()
  
      ss.xc.upload_scan = mocker.MagicMock()
      ss.xc.upload_scan.return_value = ('/data/archive/subjects/000001', exp_uri, scan_uri)
      mocker.spy(ss, '_generate_xnat_identifiers')
      ss.param = request.param
      return ss
  </code></pre>
  
  <p>If I don't pass ExperimentFactory a user id, I get this error:</p>
  
  <pre><code>TypeError: __init__() missing 1 required positional argument: 'user_id'
  </code></pre>
  
  <p>Here's the model; it makes sense to me that the factory needs an argument user_id to initialize:</p>
  
  <pre><code>class Experiment(SurrogatePK, Model):
      """A user's experiment, during which they are scanned."""
  
      __tablename__ = 'experiment'
      date = Column(db.Date(), nullable=False)
      scanner = Column(db.String(80), nullable=True)
      num_scans = Column(db.Integer(), nullable=True, default=0)
      xnat_experiment_id = Column(db.String(80), nullable=True)
      xnat_uri = Column(db.String(80), nullable=True)
      user_id = reference_col('user', nullable=False)
      scans = relationship('Scan', backref='experiment')
  
      def __init__(self, date, scanner, user_id, **kwargs):
          """Create instance."""
          db.Model.__init__(self, date=date, scanner=scanner, user_id=user_id, **kwargs)
  
      def __repr__(self):
          """Represent instance as a unique string."""
          return '&lt;Experiment({date})&gt;'.format(date=self.date)
  </code></pre>
  
  <p>But if, as written, I explicitly create a user and then pass the user id, it looks like the ExperimentFactory eventually overwrites the foreign key with the SubFactory it generated.  So later when I initialize an object called <code>ScanService</code> which must be initialized with a user_id and and experiment_id, my tests fail for one of two reasons.  Either I initialize it with the user_id of my explicitly created user, and my tests fail because they don't find any sibling experiments to the experiment that experiment_id belongs to, or I initialize it with experiment.user.id, and my tests fail because they expect one user in the database, and in fact there are two.  That latter problem would fairly easy to work around by rewriting my tests, but that seems janky and unclear.  How am I supposed to initialize the ExperimentFactory when the Experiment model requires a user_id for initialization?  </p>