def resolved_model(self, data, model, cls): """ Does all the initialization that had to wait until we knew which model we depend on. """ self.other_model = model # Create a list of all ForeignKeys and ManyToManyFields between both related models, in both directions candidates = [('forward',fk) for fk in find_fks(self.this_model,self.other_model,self.fk_name)] candidates += [('backward',fk) for fk in find_fks(self.other_model,self.this_model,self.fk_name)] candidates += [('forward_m2m',fk) for fk in find_m2ms(self.this_model,self.other_model,self.fk_name)] candidates += [('backward_m2m',fk) for fk in find_m2ms(self.other_model,self.this_model,self.fk_name)] # If a relation type was given (forward,backward,forward_m2m or backward_m2m), # filter out all relations that do not match this type. candidates = [x for x in candidates if not self.type or self.type == x[0]] if len(candidates) > 1: raise ValueError("%s has more than one ForeignKey or ManyToManyField to %s (or reverse); cannot auto-resolve." % (self.this_model, self.other_model)) if not candidates: raise ValueError("%s has no ForeignKeys or ManyToManyFields to %s (or reverse); cannot auto-resolve." % (self.this_model, self.other_model)) # Now the candidates list contains exactly one item, thats our winner. self.type, self.field = candidates[0]