serializers.py
class BuildPlanNewSerializer(serializers.ModelSerializer):
StatusName = serializers.CharField(source='BuildPlanStatusID.StatusName', read_only=True)
# build_plan_list_new = serializers.StringRelatedField(many=True, read_only=True)
total_build_plan_list = serializers.SerializerMethodField()
def get_total_build_plan_list(self, language):
return language.build_plan_list_new.count()
class Meta:
model = BuildPlanNew
fields = ('StatusName', 'total_build_plan_list')
class BuildPlanListNewSerializer(serializers.ModelSerializer):
sku = serializers.CharField(source='ProductID.sku', read_only=True)
class Meta:
model = BuildPlanListNew
fields = "__all__"
models.py
class BuildPlanNew(models.Model):
emp_id = models.ForeignKey(Employee, on_delete=models.CASCADE, null=True, blank=True)
StartDate = models.DateTimeField()
EndDate = models.DateTimeField()
BuildPlanStatusID = models.ForeignKey(GlobalStatus, on_delete=models.CASCADE)
class BuildPlanListNew(models.Model):
BuildPlanID = models.ForeignKey(BuildPlanNew, on_delete=models.CASCADE, null=True, blank=True, related_name="build_plan_list_new")
ProductID = models.ForeignKey(Product, on_delete=models.CASCADE)
TotalPlanQty = models.IntegerField()
TotalBuiltQty = models.IntegerField())
QtyPreset = models.IntegerField(default=None, max_length=256)
Objective = models.IntegerField(default=None, max_length=256)
QtyAssigned = models.IntegerField(default=None, max_length=256)
view.py
class BuildPlanNewView(viewsets.ModelViewSet):
queryset = BuildPlanNew.objects.all()
serializer_class = BuildPlanNewSerializer
class BuildPlanListNewView(viewsets.ModelViewSet):
queryset = BuildPlanListNew.objects.all()
serializer_class = BuildPlanListNewSerializer
Result i am getting:
[{
"StatusName": "1234",
"total_build_plan_list": 0
}]
Result i am expecting:
[{
"StatusName": "1234",
"total_build_plan_list": 0,
"QtyPreset_count":20,
"Objective_count":30
}]
Here i wants to fetch aggregated sum and average from foreign key table.
Need QtyPreset_count sum as QtyPreset_count
Need Objective_count sum as as Objective_count
I have shared my models views and serializers
Please have a look
just add fields to your serializer like you have done so far
from django.db.models import Sum, Avg
class BuildPlanNewSerializer(serializers.ModelSerializer):
StatusName = serializers.CharField(source='BuildPlanStatusID.StatusName', read_only=True)
# build_plan_list_new = serializers.StringRelatedField(many=True, read_only=True)
total_build_plan_list = serializers.SerializerMethodField()
QtyPreset_count = serializers.SerializerMethodField()
Objective_count = serializers.SerializerMethodField()
def get_total_build_plan_list(self, language):
return language.build_plan_list_new.count()
def get_QtyPreset_count(self, language):
return language.build_plan_list_new.aggregate(Sum('QtyPreset'))
# return language.build_plan_list_new.aggregate(Avg('QtyPreset')) if you need it's average
def get_Objective_count(self, language):
return language.build_plan_list_new.aggregate(Sum('Objective'))
class Meta:
model = BuildPlanNew
fields = ('StatusName', 'total_build_plan_list')
Related
am new to Django and currently trying the Foreign Key concept. I have three models as shown below.
class Basket(models.Model):
basket_name = models.CharField(max_length=5, unique=True)
def __str__(self):
return self.basket_name
class Product(models.Model):
Grams = 'GM'
Kilograms = 'KG'
WeightBased = 'WPG'
QuantityBased = 'CPG'
PRODUCT_UNIT_WT_CHOICES=[
(Grams, 'Grams'),
(Kilograms, 'Kilograms')
]
PRODUCT_TYPE_CHOICES =[
(WeightBased, 'Weight Based Product'),
(QuantityBased, 'Quantity Based Product')
]
product_name = models.CharField(max_length=30, unique=True)
product_description = models.TextField(max_length=300)
product_price = models.DecimalField(max_digits=5, decimal_places=2)
product_unit_weight = models.DecimalField(max_digits=5, decimal_places=2)
product_unit_weight_units = models.CharField(max_length=2, choices=PRODUCT_UNIT_WT_CHOICES, default=Grams)
product_type = models.CharField(max_length=3, choices=PRODUCT_TYPE_CHOICES, default=QuantityBased)
product_image = models.ImageField(upload_to=imageUploadPath, null=True, blank=True)
def __str__(self):
return self.product_name
class BasketProductMapping(models.Model):
basket_reference = models.ForeignKey(Basket, on_delete=models.CASCADE)
product_reference = models.ForeignKey(Product, on_delete=models.CASCADE)
mapped_basket_name = models.CharField(max_length=5,null=False, blank=False)
mapped_product_name = models.CharField(max_length=30, null=False, blank=False)
Here are my serializers:
class ProductSerializer(serializers.ModelSerializer):
product = serializers.CharField(read_only=True)
class Meta:
model = Product
fields = ['id', 'product_name', 'product_description', 'product_price', 'product_unit_weight',
'product_unit_weight_units', 'product_type', 'product_image']
class BasketSerializer(serializers.ModelSerializer):
basket = serializers.CharField(read_only=True)
class Meta:
model = Basket
fields = ('id', 'basket_name')
class BasketProductMappingSerializer(serializers.ModelSerializer):
basket_reference = serializers.CharField(source ='basket.basket_name', read_only=True)
product_reference = serializers.CharField(source='product.product_name', read_only=True)
class Meta:
model = BasketProductMapping
fields = ['id', 'basket_reference', 'product_reference', 'mapped_basket_name', 'mapped_product_name']
What I am trying to achieve is get a list of all the values in 'basket_name' and 'product_name' when I call the BasketProductMappingSerializer. But the output I am getting is this:
{
"status": 1,
"message": "Basket Product Mapping List",
"data": [
{
"id": 1,
"mapped_basket_name": "A1",
"mapped_product_name": "XYZ"
}
]
}
This is my views.py code:
class BasketProductViewSet(APIView):
def get(self, request):
if request.GET.get('id'):
print('Basket Product Mapping Details')
basketProductMappingData = BasketProductMapping.get(id = request.GET.get('id'))
serializer = BasketProductMappingSerializer(basketProductMappingData)
else:
basketProductMappingData = BasketProductMapping.objects.all().values('id', 'basket_reference__basket_name', 'product_reference__product_name', 'mapped_basket_name', 'mapped_product_name')
serializer = BasketProductMappingSerializer(basketProductMappingData, many=True)
response = {'status':1, 'message':"Basket Product Mapping List", 'data':serializer.data}
Where am I going wrong? Sorry if my question is very trivial. Thanks for your help in advance.
i see that there is an error in your views BasketProductMapping.get(id = request.GET.get('id')) should be BasketProductMapping.objects.get(id = request.GET.get('id'))
i don't know if it gonna work but can you try
basket_reference = serializers.ReadOnlyField(source ='basket.basket_name')
product_reference = serializers.ReadOnlyField(source='product.product_name')
instead of
basket_reference = serializers.CharField(source ='basket.basket_name', read_only=True)
product_reference = serializers.CharField(source='product.product_name', read_only=True)
So in order to create an object model, I have to first see if a supplier has a relation of type many to many from BusinessModel, WarehouseModel or StoreModel to in a django-polymorphic
My main idea is to check if BusinessModel, which is connected to Order through BusinessOrderModel, StoreModel, which is connected to Order through StoreOrderModel or WarehouseModel which is connected directly to Order, have FKs on a many to many relationship going to the article that we want to order through a POST request.
class ArticleModel(models.Model):
id = models.AutoField(primary_key=True)
code = models.IntegerField(unique=True)
description = models.TextField()
def __str__(self):
return str(self.code)
class OrderModel(models.Model):
id = models.AutoField(primary_key=True)
order_to = models.ForeignKey('OrderToModel', on_delete=models.CASCADE)
article = models.ForeignKey('ArticleModel', on_delete=models.CASCADE)
quantity= models.IntegerField()
class OrderToModel(PolymorphicModel):
id = models.AutoField(primary_key=True)
class WarehouseModel(OrderToModel):
warehouse_num = models.IntegerField(unique=True)
name = models.CharField(max_length=100)
address = models.TextField()
articles = models.ManyToManyField(ArticleModel)
def __str__(self):
return "Warehouse"+ str(self.warehouse_num)
class StoreOrderModel(OrderToModel):
reference = models.IntegerField(unique=True)
store_num = models.ForeignKey('StoreModel', on_delete=models.CASCADE)
def __str__(self):
return str(self.reference)
class StoreModel(models.Model):
store_num = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100)
address = models.TextField()
articles = models.ManyToManyField(ArticleModel)
def __str__(self):
return str(self.store_num)
class BusinessOrderModel(OrderToModel):
reference = models.IntegerField(unique=True)
business_num = models.ForeignKey('BusinessModel', on_delete=models.CASCADE)
def __str__(self):
return str(self.reference)
class BusinessModel(models.Model):
Business_num = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100)
address = models.TextField()
articles = models.ManyToManyField(ArticleModel)
def __str__(self):
return str(self.Business_num)
Here's my serializers:
class WarehouseSerializer(serializers.ModelSerializer):
class Meta:
model = WarehouseModel
fields = ('id', 'warehouse_num')
class StoreOrderSerializer(serializers.ModelSerializer):
class Meta:
model = StoreOrderModel
fields = ('id', 'reference', 'store_num')
class DetailSerializer(serializers.ModelSerializer):
class Meta:
model = DetailModel
fields = ('id', 'detail')
class BusinessOrderSerializer(serializers.ModelSerializer):
details = DetailSerializer(many=True, read_only=True)
class Meta:
model = BusinessOrderModel
fields = ('reference', 'business_num','details')
class OrderToPolymorphicSerializer(PolymorphicSerializer):
model_serializer_mapping = {
WarehouseModel: WarehouseSerializer,
StoreOrderModel: StoreOrderSerializer,
BusinessOrderModel: BusinessOrderSerializer
}
and here's my view:
class OrderCreateView(generics.CreateAPIView):
queryset = OrderModel.objects.all()
serializer_class = OrderCreateSerializer
I can not do relatioships between two tables without relationships.
My models are :
class exampleModel(models.Model):
quantity = models.IntegerField(blank=False, null=True)
comment = models.CharField(max_length=100 , blank=True, null=True)
class Meta:
db_table = "example"
class Logger(models.Model):
id_table = models.IntegerField()
table = models.CharField(max_length=20 , blank=True, null=True)
comment = models.CharField(max_length=100 , blank=True, null=True)
action = models.CharField(max_length=100 , blank=True, null=True)
date_created = models.DateTimeField(auto_now_add=True)
class Meta:
db_table = "logger"
I already have filled logger Model, but , I have not be able made the exampleSerializer.
My serializers are:
class LoggerSerializer(serializers.ModelSerializer):
class Meta:
db_table = u'logger'
model = Logger
fields = '__all__'
class exampleSerializer(serializers.ModelSerializer):
last_log = LoggerSerializer(read_only=True)
class Meta:
db_table = 'example'
model = ExampleModel
fields = ( 'id' , 'last_log' , 'quantity')
in logger saves :
id_table : 'primary key of example',
table : 'example'
comment : 'custom comment',
action : "CRUD"
You can query last logger in view, then pass it to serializer in context.
Then do something like:
class exampleSerializer(serializers.ModelSerializer):
last_log = serializers.SerializerMethodField()
class Meta:
db_table = 'example'
model = ExampleModel
fields = ('id', 'last_log', 'quantity')
def get_last_log(self, obj):
last_log = obj.state(self.context['last_log'])
last_log_serializer = LoggerSerializer(last_log)
return last_log_serializer.data
You pass to context, with something like:
exampleSerializer(queryset, context ={'last_log': last_log_object})
Also You can do the query in exampleSerializer:
class exampleSerializer(serializers.ModelSerializer):
last_log = serializers.SerializerMethodField()
class Meta:
db_table = 'example'
model = ExampleModel
fields = ('id', 'last_log', 'quantity')
def get_last_log(self, obj):
logger_queryset =Logger.objects.filter(table = self.Meta.db_table, id_table = obj.id)
return LoggerSerializer(logger_queryset).data
I have the following Django models:
class Product(models.Model):
name = models.CharField(max_length=250, unique=True)
quantity = models.IntegerField(default=0)
class Order(models.Model):
products = models.ManyToManyField(
Product,
through='PositionInOrder'
)
discount = models.CharField(max_length=50, blank=True)
total_sum = models.DecimalField(max_digits=11, decimal_places=2, default=0)
class PositionInOrder(models.Model):
sale = models.ForeignKey(Order)
product = models.ForeignKey(Product)
quantity = models.PositiveIntegerField()
price = models.PositiveIntegerField()
And the following serializers:
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = '__all__'
class PositionInOrderSerializer(serializers.HyperlinkedModelSerializer):
sale = serializers.ReadOnlyField()
product = serializers.ReadOnlyField()
class Meta:
model = PositionInOrder
fields = "__all__"
class OrderSerializer(serializers.ModelSerializer):
products = PositionInOrderSerializer(many=True)
def create(self, validated_data):
products = validated_data.pop('products')
order = Order.objects.create(**validated_data)
return order
class Meta:
model = Order
fields = '__all__'
I want to create new Order. Send post query which contains this json:
{
"products": [{"id": 2606, "name": "Some name", "quantity": 140, "price": 250}],
"discount": "15",
"total_sum": 500
}
And in the create() method of a class OrderSerialization I obtain that products=: [OrderedDict([('quantity', 140), ('price', 250)])] and there are no information about product_id and product_name. How can I get them?
Try to explicit define id and name fields in PositionInOrderSerializer:
class PositionInOrderSerializer(serializers.HyperlinkedModelSerializer):
sale = serializers.ReadOnlyField()
id = serializers.IntegerField(source='product.id')
name = serializers.IntegerField(source='product.name')
class Meta:
model = PositionInOrder
fields = "__all__"
Query :
I have a GET request which gives the data from the 2 models (single_tracklog_object in View). However, when I serialize this object instance using the serializers I am getting an empty data for devices as below.
{
"lat": "51.0038",
"lon": "8.0038",
"speed": 50,
"course": 5,
"device": {} # this needs to be having a value but is empty.
}
I am not understanding why its happening. Please guide me on this.
My Models :
class Tracklogs(models.Model):
tracklog_id = models.AutoField(primary_key=True)
device = models.ForeignKey(Tracking_devices, related_name='tracklogs')
lat = models.CharField(max_length=10, null=False)
lon = models.CharField(max_length=11, null=False)
.........
#timestamps
tracker_datetime = models.DateTimeField(blank=True, null=True)
class Meta:
get_latest_by = "tracker_datetime"
class Tracking_devices(models.Model):
device_id = models.AutoField(primary_key=True)
device_type = models.ForeignKey(Device_type)
user = models.ForeignKey(User, null=False)
name = models.CharField(max_length=100)
description = models.CharField(max_length=256, blank=True, null=True)
My View :
serializer_class = ShowLocationInfoSerializer
def get(self, request, *args, **kwargs):
# get the imei from the url
imei = self.kwargs['imei']
try:
single_tracklog_object = Tracklogs.objects.filter(device__imei = imei).values('lat', 'lon','speed','course','device','device__name').latest()
# Here its causing problem!!!
serializer = self.serializer_class(single_tracklog_object)
return Response(serializer.data)
except ObjectDoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
My Serializer:
class Tracking_DeviceSerializer(serializers.ModelSerializer):
name = serializers.CharField(read_only=True)
class Meta:
model = Tracking_devices
fields = ('name')
class ShowLocationInfoSerializer(serializers.ModelSerializer):
lat = serializers.CharField(read_only=True)
lon = serializers.CharField(read_only=True)
speed = serializers.IntegerField(read_only=True)
course = serializers.FloatField(read_only=True)
device = Tracking_DeviceSerializer()
class Meta:
model = Tracklogs
fields = ('lat', 'lon', 'tracker_datetime', 'speed', 'course', 'device' )
Thanks in advance.