Así que tengo:
Perfil del usuario:
class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile', unique=False) orders = models.ManyToManyField(Order, blank=True)Ordenar:
class Order(models.Model): car_brand = models.CharField(max_length=30) car_model = models.CharField(max_length=30) repair_type = models.CharField(max_length=30)Registro.js:
... // Handling the form submission const handleSubmit = (e) => { e.preventDefault(); if (name === '' || email === '' || password === '') { setError(true); } else { console.log('component Register registering ') let user = { username: name, email: email, password: password, is_active: false, } axios.post('http://localhost:8000/api/users/', { username: name, email: email, password: password, is_active: false, }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error.response); }); axios.post('http://localhost:8000/api/profiles/', { user: null, orders: [] }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error.response); }); setSubmitted(true); setError(false); } }; ...La pregunta es:
La creación de usuarios funciona bien, se crea el usuario, se muestra en el rest-api y .db
¿Cómo crear un perfil de usuario? ¿Cómo puedo agregar un usuario, que creé primero, y agregar la lista de pedidos vacíos?
Creo que necesita configurar OrderSerializer en UserProfileSerializer .
class UserProfileSerializer(serializers.ModelSerializer): orders = OrderSerializer(many = True) user_id = serializers.IntegerField(write_only = True) user = UserSerializer(read_only = True) class Meta: model = UserProfile fields = ['user', 'orders', 'user_id'] def create(self, validated_data): order_ids = [] order_data = validated_data.pop('orders') for order_item in order_data: new_order = Order.objects.create(**order_item) order_ids.append(new_order.id) new_profile = UserProfile.objects.create(user_id = validated_data['user_id']) new_profile.set(order_ids) return new_profileLuego, en la API posterior, debe cargar user_id y pedidos como los siguientes. Aquí asumo que el usuario ya se ha creado y es necesario crear pedidos.
{ "user_id": 1, "orders": [ { "car_brand": "...", "car_model": "...", "repair_type": "..." }, ... ] }Por supuesto, puede crear un usuario cuando crea un perfil de usuario, pero para hacerlo, puede cambiar un poco el código.