Добавьте промежуточные поля модели для обратного отношения
У меня есть две связанные модели (Product и Recipe). Между ними определено отношение "многие-ко-многим" (с моделью through
). Я могу запросить "сквозные" поля модели, используя приведенный ниже сериализатор, но я не могу заставить это работать в обратном направлении (от Product к Recipe)
models.py:
class Product(models.Model):
version = models.CharField(max_length=4)
displayname = models.CharField(max_length=50,validators=[alphanumeric])
...
class Recipe(models.Model):
...
ingredients = models.ManyToManyField(Product, through='RecipeInput', related_name='recipe_input')
products = models.ManyToManyField(Product, through='RecipeOutput',related_name='recipe_output')
class RecipeInput(models.Model):
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
amount = models.IntegerField(default=1)
amount_min = models.FloatField(blank=True, null=True)
class RecipeOutput(models.Model):
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
amount = models.IntegerField(default=1)
amount_min = models.FloatField(blank=True, null=True)
mj = models.FloatField(blank=True, null=True)
serializers.py:
class RecipeInputSerializer(serializers.HyperlinkedModelSerializer):
product_id = serializers.ReadOnlyField(source='product.id')
product_name = serializers.ReadOnlyField(source='product.displayname')
class Meta:
model = RecipeInput
fields = ('product_id',"product_name", 'amount', 'amount_min', )
class RecipeOutputSerializer(serializers.HyperlinkedModelSerializer):
product_id = serializers.ReadOnlyField(source='product.id')
product_name = serializers.ReadOnlyField(source='product.displayname')
class Meta:
model = RecipeOutput
fields = ('product_id',"product_name", 'amount', 'amount_min', 'mj', )
class ProductInputSerializer(serializers.HyperlinkedModelSerializer):
recipe_id = serializers.ReadOnlyField(source='recipe.id')
recipe_name = serializers.ReadOnlyField(source='recipe.displayname')
class Meta:
model = RecipeInput
fields = ('recipe_id','recipe_name', 'amount_min', 'amount', )
class RecipeSerializer(serializers.ModelSerializer):
ingredients = RecipeInputSerializer(source='recipeinput_set', many=True)
products = RecipeOutputSerializer(source='recipeoutput_set', many=True)
class Meta:
model = Recipe
fields = "__all__"
depth = 1
class ProductSerializer(serializers.ModelSerializer):
products_in = ProductInputSerializer(source='recipe_input', many=True)
class Meta:
model = Product
fields = "__all__"
depth = 1
Теперь, это работает для Recipe, я получаю следующий вывод:
[
{
"id": 1239,
"ingredients": [
{
"product_id": 1787,
"product_name": "Automated Wiring",
"amount": 15,
"amount_min": 7.5
},
{
"product_id": 1799,
"product_name": "Circuit Board",
"amount": 10,
"amount_min": 5.0
}
],
"products": [
{
"product_name": "Adaptive Control Unit",
"amount": 2,
"amount_min": 1.0,
"mj": 3300.0
}
],
...
},
{
"id": 1240,
"ingredients": [
{
"product_id": 1809,
"product_name": "Copper Sheet",
"amount": 5,
"amount_min": 25.0
},
{
"product_id": 1871,
"product_name": "Quickwire",
"amount": 20,
"amount_min": 100.0
}
],
"products": [
{
"product_name": "AI Limiter",
"amount": 1,
"amount_min": 5.0,
"mj": 180.0
}
],
...
}
]
Но для Product я не могу запросить связанную модель (Recipe) и значения сквозной модели. В serializers.py я определил products_in
, но он не показывает recipe_id, recipe_name, etc.
[
{
"id": 2541,
"products_in": [
{
"amount_min": null
}
],
...
},
{
"id": 2542,
"products_in": [
{
"amount_min": null
},
{
"amount_min": null
}
],
...
}
]