This is my model.py
class AppointmentMaster(models.Model):
id = models.AutoField(primary_key=True)
user_key = models.CharField(max_length=30,blank=True,unique=True)
phone_number = models.CharField(max_length=20, blank=True, null=True)
email = models.CharField(max_length=20, blank=True, null=True)
@receiver(post_save, sender=AppointmentMaster)
def generate_AppointmentMaster_unique_key(sender, instance, created, **kwargs):
post_save.disconnect(generate_AppointmentMaster_unique_key, sender=MenstrualHistory)
instance.menstrual_history_n_key = "USER-{}".format(instance.id)
instance.save()
post_save.connect(generate_AppointmentMaster_unique_key, sender=AppointmentMaster)
and i'm using viewsets.ModelViewSet for post details.I want to save user_key automatically when create a new row from post api.
I want output like
{
"id":1,
"user_key":"USER-1",
"phone_number":"90000000",
"email":"[email protected]"
}
CodePudding user response:
You can override the .save()
method in Model
that will automatically perform this action when ever you update
or create
an object.
class AppointmentMaster(models.Model):
id = models.AutoField(primary_key=True)
user_key = models.CharField(max_length=30,blank=True,unique=True)
phone_number = models.CharField(max_length=20, blank=True, null=True)
email = models.CharField(max_length=20, blank=True, null=True)
def save(self, *args, **kwargs):
self.user_key = f"USER-{self.id}"
super(AppointmentMaster, self).save(*args, **kwargs)
CodePudding user response:
I don't use viewsets much. If you can steer away from them with your app this might work. I'd also recommend using the pk which already comes with each model instance instead of your 'id' field, which I assume serves a similar purpose.
yourapp.views.py
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['POST'])
def yourView(request):
if request.method == "POST":
data = request.POST
appt = AppointmentMaster()
appt.user_key = data.get('user_key')
appt.phone_number = data.get("phone_number")
appt.email = data.get("email")
appt.save()
return Response('id':appt.id, 'user_key':appt.user_key, 'phone_number':appt.phone_number, 'email':appt.email)
You may need to include some additional error checking to ensure the instance was properly saved and possibly query it from the db in order for the 'appt.id' to work properly in the response. that would entail you adding:
...
appt.save()
newAppt = AppointmentMaster.objects.get(user_key=data.get('user_key'))
and then replacing all response parameters with 'newAppt' instead of 'appt'. Hope this helped and I understood your question :D