Python
2
Вклад в тег
class Item(models.Model):
name = models.CharField(max_length=255)
price = models.DecimalField(max_digits=16, decimal_places=2)
class ConvertedPrice(models.Model):
item = models.ForeignKey(Item, on_delete=models.CASCADE)
currency = models.CharField(max_length=3)
value = models.DecimalField(max_digits=16, decimal_places=2)
ordered_items = Item.objects.annotate(converted=Subquery(
ConvertedPrice.objects.filter(item=OuterRef('id'), currency='USD').values('value')
)).order_by('converted')
SELECT
"app_item"."id",
"app_item"."name",
"app_item"."price",
(
SELECT U0."value"
FROM "app_convertedprice" U0
WHERE (U0."currency" = USD AND U0."item_id" = ("app_item"."id"))
) AS "converted"
FROM "app_item"
ORDER BY "converted" ASC;
def __new__(cls):
if cls.instance is None:
cls.instance = object.__new__(cls)
return cls.instance
class ClassA:
pass
instance = object.__new__(ClassA) # <ClassA object at 0x0....>
class VendorManagementUpdateSerializer(serializers.ModelSerializer):
...
parent = VendorToFrontSerializer()
...
class Meta:
model = Vendors
fields = (..., 'parent', ...)
def create(self, validated_data, **kwargs):
parent = validated_data.pop('parent')
instance = super().create(validated_data, **kwargs)
parent_serializer = VendorToFrontSerializer(data=parent)
if parent_serializer.is_valid():
instance.parent = parent_serializer.save()
return instance
def update(self, instance, validated_data, **kwargs):
# ...точно так же, только нужно будет уже имеющийся объект обновить