I have a Business model and Order model. Businesses can order furniture in our website. A user creates an account and makes an order. Since he is a new user, he is not associated to any Business. In the order form, he will give the information about his business and some information related to current order. A new Business record and Order record will be created with the given info. There’s a foreign key for Business in Order table.
If he wants to create a second order, since he has already a business, he will have the business info pre-filled in his form. When he gives the order data and submits, backend won’t create a new Business record. It only creates Order record and store the Business reference.
How do I achieve this in single endpoint to create update and retrieve?
# serializers.py
import time
class BusinessSerializer(serializers.ModelSerializer):
class Meta:
model = Business
fields = '__all__'
def create(self, validated_data):
timestamp = int(time.time())
random_number = random.randint(100,999)
validated_data['code'] = f'BUSINESS-{timestamp}'
validated_data['status'] = 'CREATED'
return super().create(validated_data)
class OrderSerializer(serializers.ModelSerializer):
class Meta:
model = Order
fields = '__all__'
def create(self, validated_data):
timestamp = int(time.time())
random_number = random.randint(100,999)
validated_data['code'] = f'ORDER-{timestamp}'
validated_data['status'] = 'CREATED'
return super().create(validated_data)
# views.py
class BusinessOrderAPIView(generics.CreateAPIView):
permission_classes = [IsAuthenticated]
queryset = Order.objects.all()
serializer_class = OrderSerializer
def perform_create(self, serializer):
business_data = self.request.data.get('business', {})
business_id = business.get('id')
if business_id:
try:
business = Business.objects.get(pk=business_id)
except Business.DoesNotExist:
business = Business.objects.create()
business.name = business_data.get('name')
business.website = business_data.get('website')
business.address = business_data.get('address')
business.city = business_data.get('city')
business.state = business_data.get('state')
business.country = business_data.get('country')
business.save()
order = serializer.save(business=business.pk)
This is how my request would look
{
"chairs": 3,
"tables": 1,
"delivery_type": "ONE_DAY",
"payment_type": "CASH_ON_DELIVERY",
"business": {
"name": "Vin.AI",
"website": "https://lol.com",
"address": "My street",
"city": "Gotham City",
"state": "New York",
"country": "USA",
}
}