eliataylor / object-actions

An interactive worksheet and CMS builder
Other
0 stars 3 forks source link

Upsert referenced data on create / update #6

Closed eliataylor closed 5 months ago

eliataylor commented 5 months ago

POST / PATCHs requests to each endpoint should accept referenced (foreign key) data as either an ID or object.

I imagine this will be done in serializer for example something like:

class MealSerializer(serializers.ModelSerializer):
    ingredients = IngredientSerializer(many=True)

    class Meta:
        model = Meal
        fields = ['id', 'name', 'ingredients']

    def create(self, validated_data):
        ingredients_data = validated_data.pop('ingredients')
        if isinstance(ingredients_data, list):
            meal = Meal.objects.create(**validated_data)
            for ingredient_data in ingredients_data:
                if 'id' in ingredient_data:
                    meal.ingredients.add(ingredient['id'])
                else: 
                    ingredient, created = Ingredient.objects.get_or_create(
                        name=ingredient_data['name'], 
                        defaults={....}
                    )
                   meal.ingredients.add(ingredient)
        elif isinstance(ingredients_data, str): 
             # if uuid or slug, query for reference to validate....
        elif isinstance(ingredients_data, int): # maybe check for uuid, 
              # handle direct reference
        return meal

    def update(self, instance, validated_data):
...