开发者

Check if record exists before saving

开发者 https://www.devze.com 2022-12-19 18:46 出处:网络
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 us

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(Mess开发者_运维知识库ageType)
   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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消