DRF обновление вложенного внешнего ключа объекта
I am trying to wrap my head around this for too long already :( I need the following output for my frontend (specially the ID
& name
field in combination):
{ "serial": "e3461fb0", "shipment": { "id": 1, "name": "via rotterdam" } }
модель:
class Shipment(models.Model):
name = models.CharField("name", max_length = 128)
date = models.DateField()
class Product(models.Model):
serial = models.CharField("serial", max_length = 31, unique = True)
shipment = models.ForeignKey(Shipment, on_delete = models.CASCADE, blank = True, null = True)
сериализатор:
class ShipmentSerializer(serializers.ModelSerializer):
class Meta:
model = Shipment
fields = ["id", "name",]
class ProductSerializer(serializers.ModelSerializer):
shipment = ShipmentSerializer()
def update(self, instance, validated_data):
print("TEST:", instance, validated_data)
return super().update(instance, validated_data)
class Meta:
model = Product
fields = ["serial", "shipment",]
lookup_field = "serial"
read_only_fields = ["serial",]
Видовой набор:
class ProductViewSet(ModelViewSet):
serializer_class = ProductSerializer
lookup_field = "serial"
http_method_names = ["get", "patch", "put"]
def get_queryset(self):
return Product.objects.all()
my problem here is the following: Lets say a product ist linked to a shipment and what I want now is to update that product by linking it to another shipment by using the id
. But even in the HTML view of DRF I only get to see the name
attribute of shipment
. How can I only show/use the id
here? I know I could modify the __str__
method of the model to return a string representation and split it later in the frontend, but I would like to avoid that if possible.
Я думал о чем-то подобном:
Поле Id - это то, что DRF делает сам, и по умолчанию оно доступно только для чтения
Если вы хотите обновить это, вам следует переопределить это поле. Что-то вроде:
class ShipmentSerializer(serializers.ModelSerializer):
id = serializers.IntegerField()
name = serializers.CharField(read_only=True)
class Meta:
model = Shipment
fields = ["id", "name",]