Answer the question
In order to leave comments, you need to log in
Django Rest Framework How to get instance foreign key?
I will explain the essence, since the vocabulary is not rich in terms.
When creating a new App_form, a ChosenProduct
is
added that contains a product from Warehouse
and the amount of product added to ChosenProduct is reduced.
Now, when App_form is changed, that is, the value of terminated is changed to true by the patch method , this App_form gets, say, into the archive, and at the same time, the products from chosen_products should return to the Warehouse as a quantity , and after chosen_products is cleared.
class WarehouseSerializer(serializers.ModelSerializer):
category_name = serializers.ReadOnlyField(
source='category_product.category_name')
posted_user = serializers.ReadOnlyField(
source='posted_user.username')
class Meta:
model = Warehouse
fields = ['id', 'category_product', 'category_name', 'condition',
'product_name', 'amount', 'barcode', 'f_price', 'created_at', 'updated_at', 'posted_user']
class ChosenProductSerializer(serializers.ModelSerializer):
product_info = WarehouseSerializer(source='product', read_only=True)
period_info = Product_periodSerializer(source='period', read_only=True)
class Meta:
model = ChosenProduct
exclude = ('app_form',)
class App_formSerializer(serializers.ModelSerializer):
chosen_products = ChosenProductSerializer(many=True)
@transaction.atomic
def create(self, validated_data):
chosen_products_data = validated_data.pop('chosen_products')
app_form = App_form.objects.create(**validated_data)
for chosen_product_data in chosen_products_data:
chosen_product = ChosenProduct.objects.create(app_form=app_form, **chosen_product_data)
product = chosen_product.product
product.amount = product.amount - chosen_product.quantity
product.save()
return app_form
def update(self, instance, validated_data):
instance.terminated = validated_data.get('terminated', instance.terminated)
if instance.terminated == True :
print('-----------TRUE--------------------')
print(instance.chosen_products)
print('-----------PRINT--------------------')
instance.save()
return instance
class Meta:
model = App_form
fields = '__all__'
-----------TRUE--------------------
creditapi.ChosenProduct.None
-----------PRINT--------------------
Answer the question
In order to leave comments, you need to log in
Implement a model method that does what you want and just call it in update.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question