tags:

views:

61

answers:

1

I have a Customer class linked to several other classes via foreign key. I want to have the forms working in such a way that if the submitted customer record already exists, then this record will be used as the foreign key for the dependent class.

I've declared the Customer class as:

class Customer(CustomerBaseInfo):
   date_time_added = models.DateTimeField(default=datetime.today)
   source = models.ForeignKey(Source, blank=False)
   email_address = models.CharField(max_length=75)
   phone_number = models.CharField(max_length=20)
   preffered_contact_method = models.ForeignKey(PreferredContact)
   best_time_to_contact = models.ForeignKey(BestTime)
   def __unicode__(self):
     return self.first_name

One of the classes that link to the Customer class look like this:

class Message(models.Model):
   date_time_added = models.DateTimeField(default=datetime.today)
   message_type = models.ForeignKey(MessageType)
   customer = models.ForeignKey(Customer)
   representative = models.ForeignKey(Representative)
   vehicle = models.CharField(max_length=80)
   message = models.TextField(null=True)
   def __unicode__(self):
     return self.date_time_added
+3  A: 

get_or_create() will return the model after creating it if it does not exist.

Ignacio Vazquez-Abrams
works just fine...thanks
Stephen