Django Rest Framework serilize relations - django

How to serialize a fields in related models.
I got a models:
class Order(models.Model):
order_id = models.BigIntegerField(verbose_name='Order ID', unique=True)
order_name = models.CharField(verbose_name='Order name', max_length=255)
order_type = models.IntegerField(verbose_name='Campaign type')
class Types(models.Model):
delimiter = models.CharField(verbose_name='Delimiter', max_length=255)
status = models.BooleanField(verbose_name='Status', default=True)
title = models.CharField(verbose_name='Title', max_length=255)
class User(models.Model):
name = models.CharField(verbose_name='User name', max_length=200, unique=True)
class Report(models.Model):
order = models.ForeignKey(Order, to_field='order_id', verbose_name='Order ID')
user = models.ForeignKey(User, verbose_name='User ID')
ad_type = models.ForeignKey(Types, verbose_name='Type')
imp = models.IntegerField(verbose_name='Total imp')
month = models.DateField(verbose_name='Month', default=datetime.datetime.today)
View:
class ReportLisAPIView(ListAPIView):
serializer_class = ReportSerializer
def get_queryset(self):
month = parse_date(self.kwargs['month']) - relativedelta(day=1)
queryset = (
Report.objects.filter(month=month)
.values_list(
'user', 'user__name', 'order__order_id',
'order__order_name', 'order__order_type'
).all().annotate(Sum('imp'))
)
return queryset
Serializer:
class ReportSerializer(ModelSerializer):
class Meta:
model = Report
depth = 1
I need to get all field like in 'queryset' in get_queryset()
but I got an error:
Got AttributeError when attempting to get a value for field imp on
serializer ReportSerializer. The serializer field might be named
incorrectly and not match any attribute or key on the tuple
instance. Original exception text was: 'tuple' object has no attribute
'imp'.
But if I return in get_queryset() just Report.objects.filter(month=month).all() I'll get all objects and related object with all field, without aggregate of imp and not grouping.
So the question is how to make serializer return structure that set in queryset?

The get_queryset method requires to return a queryset but you are returning a tuple beacause of values_list. Either drop it to return a queryset or go with a more generic view like APIView.

I found a way how to do it.
As I use .values_list() it return list object instead of queryset object. So for serializer do understand what is inside the list I defined all fields in serializer. And in to_representation() I return dictionary like it should be.
Serializer:
class ReportSerializer(serializers.ModelSerializer):
user = serializers.IntegerField()
user_name = serializers.CharField()
order_id = serializers.IntegerField()
order_name = serializers.CharField()
order_type = serializers.IntegerField()
imp = serializers.IntegerField()
class Meta:
model = Report
fields = [
'user', 'user_name', 'order_id', 'order_name',
'order_type', 'imp'
]
depth = 1
def to_representation(self, instance):
Reports = namedtuple('Reports', [
'user',
'user_name',
'order_id',
'order_name',
'order_type',
'imp',
])
return super(ReportSerializer, self).to_representation(
Reports(*instance)._asdict()
)
View:
class ReportLisAPIView(ListAPIView):
serializer_class = ReportSerializer
def get_queryset(self):
month = parse_date(self.kwargs['month']) - relativedelta(day=1)
queryset = (
Report.objects.filter(month=month)
.values_list(
'user', 'user__name', 'order__order_id',
'order__order_name', 'order__order_type'
).all().annotate(Sum('imp'))
)
return queryset
def list(self, *args, **kwargs):
queryset = self.get_queryset()
serializer = self.serializer_class(queryset, many=True)
# actualy that's it! part of which is below can be pass and just
# return Response(serializer.data)
result = {
'month': parse_date(self.kwargs['month']).strftime('%Y-%m'),
'reports': []
}
inflcr = {}
for item in serializer.data:
inflcr.setdefault(item['user'], {
'id': item['user'],
'name': item['user_name'],
'campaigns': []
})
orders = {
'id': item['order_id'],
'name': item['order_name'],
'type': item['order_type'],
'impressions': item['imp'],
}
inflcr[item['user']]['campaigns'].append(orders)
result['reports'] = inflcr.values()
return Response(result)

Related

How can I show the StringRelatedField instead of the Primary Key while still being able to write-to that field using Django Rest Framework?

Models:
class CrewMember(models.Model):
DEPARTMENT_CHOICES = [
("deck", "Deck"),
("engineering", "Engineering"),
("interior", "Interior")
]
first_name = models.CharField(max_length=25)
last_name = models.CharField(max_length=25)
email = models.EmailField()
department = models.CharField(max_length=12, choices=DEPARTMENT_CHOICES)
date_of_birth = models.DateField()
join_date = models.DateField()
return_date = models.DateField(null=True, blank=True)
leave_date = models.DateField(null=True, blank=True)
avatar = models.ImageField(null=True, blank=True)
active = models.BooleanField(default=True)
def __str__(self):
return f"{self.first_name} {self.last_name}"
class RosterInstance(models.Model):
date = models.DateField(default=timezone.now)
deckhand_watchkeeper = models.ForeignKey(CrewMember, on_delete=models.PROTECT, null=True, related_name="deckhand_watches")
night_watchkeeper = models.ForeignKey(CrewMember, on_delete=models.PROTECT, null=True, related_name="night_watches")
def __str__(self):
return self.date.strftime("%d %b, %Y")
Views:
class CrewMemberViewSet(viewsets.ModelViewSet):
queryset = CrewMember.objects.all()
serializer_class = CrewMemberSerializer
filter_backends = [SearchFilter]
search_fields = ["department"]
def destroy(self, request, *args, **kwargs):
instance = self.get_object()
instance.active = False
instance.save()
return Response(status=status.HTTP_204_NO_CONTENT)
class RosterInstanceViewSet(viewsets.ModelViewSet):
queryset = RosterInstance.objects.all()
serializer_class = RosterInstanceSerializer
Serializers:
class CrewMemberSerializer(serializers.ModelSerializer):
class Meta:
model = CrewMember
fields = "__all__"
class RosterInstanceSerializer(serializers.ModelSerializer):
class Meta:
model = RosterInstance
fields = "__all__"
The resulting data looks like this:
{
"id": 2,
"date": "2020-12-09",
"deckhand_watchkeeper": 1,
"night_watchkeeper": 3
}
But I want it to look like this:
{
"id": 2,
"date": "2020-12-09",
"deckhand_watchkeeper": "Joe Soap",
"night_watchkeeper": "John Smith"
}
I can achieve the above output by using StringRelatedField in the RosterInstanceSerializer but then I can no longer add more instances to the RosterInstance model (I believe that is because StringRelatedField is read-only).
Because StringRelaredField is always read_only, you can use SlugRelatedField instead:
class RosterInstanceSerializer(serializers.ModelSerializer):
deckhand_watchkeeper = serializers.SlugRelatedField(
slug_field='deckhand_watchkeeper'
)
night_watchkeeper = serializers.SlugRelatedField(
slug_field='night_watchkeeper'
)
class Meta:
model = RosterInstance
fields = ['id', 'date', 'deckhand_watchkeeper', 'night_watchkeeper']
I was created a WritableStringRelatedField to do that.
class WritableStringRelatedField(serializers.SlugRelatedField):
def __init__(self, display_field=None, *args, **kwargs):
self.display_field = display_field
# Set what attribute to be represented.
# If `None`, use `Model.__str__()` .
super().__init__(*args, **kwargs)
def to_representation(self, obj):
# This function controls how to representation field.
if self.display_field:
return getattr(obj, self.display_field)
return str(obj)
def slug_representation(self, obj):
# It will be called by `get_choices()`.
return getattr(obj, self.slug_field)
def get_choices(self, cutoff=None):
queryset = self.get_queryset()
if queryset is None:
# Ensure that field.choices returns something sensible
# even when accessed with a read-only field.
return {}
if cutoff is not None:
queryset = queryset[:cutoff]
return OrderedDict([
(
self.slug_representation(item),
# Only this line has been overridden,
# the others are the same as `super().get_choices()`.
self.display_value(item)
)
for item in queryset
])
Serializers:
class RosterInstanceSerializer(serializers.ModelSerializer):
deckhand_watchkeeper = WritableStringRelatedField(
queryset=CrewMember.objects.all(),
slug_field='id',
label='Deckhand Watchkeeper',
)
night_watchkeeper = WritableStringRelatedField(
queryset=CrewMember.objects.all(),
slug_field='id',
label='Night Watchkeeper',
)
class Meta:
model = RosterInstance
fields = "__all__"

Nested JSON and HyperlinkedModelSerializer problem

I'm working on a tweet App. I have 2 main models : Tweets and Comments. I'm using HyperlinkedModelSerializer to get absolute url for my comments instances with the "url" added in the field. But when It comes to display the comments inside my tweet JSON format, i have this error :
`HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer.
This error is gone when I remove the url from the field.
Here is my Comment Model :
class CommentManager(models.Manager):
def filter_by_instance(self, instance):
content_type = ContentType.objects.get_for_model(instance.__class__)
obj_id = instance.id
qs = super(CommentManager, self).filter(content_type=content_type, object_id=obj_id)
return qs
class Comment(models.Model):
content = models.TextField(max_length=150)
author = models.ForeignKey(
User,
on_delete = models.CASCADE
)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField(blank=True)
content_object = GenericForeignKey('content_type', 'object_id')
parent = models.ForeignKey(
"self",
on_delete = models.CASCADE,
blank=True,
null=True
)
datestamp = models.DateTimeField(auto_now_add=True)
objects = CommentManager()
def __str__(self):
return str(self.content[:30])
def save(self):
self.object_id = self.parent.id
super(Comment, self).save()
def children(self):
return Comment.objects.filter(parent=self)
#property
def is_parent(self):
if self.parent is None:
return False
return True
Here is my comment serializer :
class CommentSerializer(serializers.HyperlinkedModelSerializer):
children = serializers.SerializerMethodField()
datestamp = serializers.SerializerMethodField()
def get_datestamp(self, obj):
return obj.datestamp.date()
def get_children(self, obj):
qs = obj.children()
return ChildrenCommentSerializer(qs, many=True).data
class Meta:
model = Comment
fields = [
"url",
"datestamp",
"content",
"is_parent",
"object_id",
"children"
]
class ChildrenCommentSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
fields = [
"content"
]
And finally my tweet serializer :
class TweetSerializer(serializers.ModelSerializer):
author = serializers.SlugRelatedField(slug_field="username", queryset=User.objects.all())
comments = serializers.SerializerMethodField()
datestamp = serializers.SerializerMethodField()
def get_datestamp(self, obj):
return obj.datestamp.date()
def get_comments(self, obj):
qs = Comment.objects.filter_by_instance(obj)
print()
print()
print(CommentSerializer(qs, many=True))
print()
print()
return CommentSerializer(qs, many=True).data
class Meta:
model = Tweet
fields = ["datestamp", "id", "content", "author", "nb_likes", "nb_comments", "slug", "comments" ]
def to_representation(self, obj):
representation = super().to_representation(obj)
if obj.nb_likes > 50:
representation['super_popular'] = True
return representation
I do not understand how and where in the code i should add the "context={'request': request}"
place it when instantiating the serializer
class ViewExample(APIView):
def get(self, request, pk, format=None):
listexample = Example.objects.all()
serializer = ExampleSerializer(listexample, many=True, context={'request':request})
return Response(serializer.data, status=status.HTTP_200_OK)

Overwrite fields in Django Serializer

I am new in Django and I would like to overwrite the field value in create and update method of serializer. Here is my model=>
class Holiday(models.Model):
HolidayDay = models.DateField()
Created_DT = models.DateTimeField()
Created_Usr = models.CharField(max_length=20)
LastModified_Usr = models.CharField(max_length=20,blank=True)
LastModified_DT = models.DateTimeField(blank=True,null=True)
def __str__(self):
return str(self.HolidayDay)
Here is my serializer=>
class HolidaySerializer(serializers.ModelSerializer):
class Meta:
model=Holiday
fields = [
'id',
'HolidayDay',
'Created_DT',
'Created_Usr',
'LastModified_Usr',
'LastModified_DT'
]
def create(self,validated_data):
validated_data['Created_Usr'] ="Testing"
return Holiday.objects.create(**validated_data)
I would like to update Create_usr field value in create method and LastModified_usr field in update method. But why I can't overwrite the create_usr field as "Testing"?
Here is my views=>
def post(self,request):
holiday = request.data.get('holiday')
serializer = HolidaySerializer(data=holiday)
serializer.is_valid()
print(serializer.errors)
if serializer.is_valid():
holiday_saved=serializer.save()
return Response({"success":"Holiday '{}' created successfully".format(holiday_saved.HolidayDay)})
def put(self,request,pk):
save_holiday = get_object_or_404(Holiday.objects.all(),pk=pk)
data = request.data.get('holiday')
serializer = HolidaySerializer(instance=save_holiday,data=data,partial=True)
if serializer.is_valid(raise_exception = True):
holiday_saved=serializer.save()
return Response({"sucess": "Holiday '{}' updated successfully".format(holiday_saved.HolidayDay)})
Your create method is not defined in your Serializer class, instead it is part of your Meta class. You should be able to solve it by moving your create method to your HolidaySerializer:
class HolidaySerializer(serializers.ModelSerializer):
def create(self,validated_data):
validated_data['Created_Usr'] = "Testing"
return Holiday.objects.create(**validated_data)
class Meta:
model=Holiday
fields = [
'id',
'HolidayDay',
'Created_DT',
'Created_Usr',
'LastModified_Usr',
'LastModified_DT'
]

How to Change ManyToManyField Name in Serializer

I want to change ManyToManyField Name. user_groups is manytomanyfield. I tried to use ManyToManyRelatedField and also PrimaryKeyRelatedField but it is giving error. How can i change or with data type should i give like for character field i am giving CharField
class EmployeeProfileSerializer(serializers.ModelSerializer):
employee_id = serializers.CharField(source='user_employee_id')
payroll_id = serializers.CharField(source='user_payroll_id')
phone = serializers.CharField(source='user_phone')
hire_date = serializers.DateField(source='user_hire_date')
pay_rate = serializers.IntegerField(source='user_pay_rate')
salaried = serializers.CharField(source='user_salaried')
excempt = serializers.CharField(source='user_excempt')
state = serializers.CharField(source='user_state')
city = serializers.CharField(source='user_city')
zipcode = serializers.IntegerField(source='user_zipcode')
status = serializers.CharField(source='user_status')
class Meta:
model = UserProfile
fields = [
'employee_id',
'phone',
'payroll_id',
'hire_date',
'pay_rate',
'salaried',
'excempt',
'state',
'city',
'zipcode',
'status',
'user_groups',
]
You can use SerializerMethodField:
class EmployeeProfileSerializer(serializers.ModelSerializer):
...
your_custom_name = SerializerMethodField()
class Meta:
model = UserProfile
fields = ['your_custom_name ', ...]
def get_your_custom_name(self, obj):
# Return ids:
return list(obj.user_groups.all().values_list('pk', flat=True))
# Or using a serializer:
return MyUserGroupSerializer(obj.user_groups.all(), many=True).data
For create and update you have to override the create and update method to assign the new field:
class EmployeeProfileSerializer(serializers.ModelSerializer):
...
your_custom_name = IntegerField()
class Meta:
model = UserProfile
fields = ['your_custom_name', ...]
# If you need validation
def validate_your_custom_name(self, value):
if value:
if int(value) > 5:
return value
return None
def create(self, validated_data):
# Get the data for your new field
my_costum_data = validated_data.get('your_custom_name')
# Do something with it
profile_obj = UserProfile.objects.create(...)
if my_costum_data:
user_group = UserGroupModel.objects.get(pk=int(my_costum_data))
profile_obj.user_groups.add(user_group)
def update(self, instance, validated_data):
# Same as create()
...

Django REST Framework, PUT/POST serializer data disappearing

I am having trouble with part of my data disappearing when I try to update or post a new instance.
With data like this
data = {
'item': 'Product',
'station': 'Workbench',
'ingredients':[
{'item': 'ing1', 'amount': 2},
{'item': 'ing2', 'amount':1}
]
}
I have a serializer with a nested serializer that get_or_creates ingredients as needed.
class IngredientSerializer(serializers.ModelSerializer):
class Meta:
model = Ingredient
fields = ('item', 'amount')
class WriteableRecipeSerializer(serializers.ModelSerializer):
item = serializers.PrimaryKeyRelatedField(queryset=Item.objects.all())
ingredients = IngredientSerializer(many=True)
station = serializers.PrimaryKeyRelatedField(queryset=Item.objects.all())
def create(self, validated_data):
logger.info(validated_data)
ingredient_data = validated_data.pop('ingredients')
recipe = Recipe.objects.create(**validated_data)
for ingredient in ingredient_data:
ingredient_item = Item.objects.get(name=ingredient['item'])
amount = ingredient['amount']
ingredient, created = Ingredient.objects.get_or_create(item=ingredient_item, amount=amount
)
recipe.ingredients.add(ingredient)
return recipe
def update(self, instance, validated_data):
logger.info(validated_data)
ingredient_data = validated_data.pop('ingredients')
instance.item = validated_data.get('item', instance.item)
instance.station = validated_data.get('station', instance.station)
for ingredient in ingredient_data:
ingredient_item = Item.objects.get(name=ingredient['item'])
amount = ingredient['amount']
ingredient, created = Ingredient.objects.get_or_create(item=ingredient_item, amount=amount)
logger.info('Itering')
instance.ingredients.add(ingredient)
return instance
class Meta:
model = Recipe
fields = ('item', 'amount', 'ingredients', 'station')
The data validates and I get a response code 200, but both the response data and the validated_data a shown by my logger in the create and update methods return something like this:
data = {
'item': 'Product',
'station': 'Workbench',
'ingredients':[]
}
The Ingredients data going AWOL somewhere.
I have tried making the Ingredient Serializer a generic serializer as well as overriding WriteableRecipeSerializer's validation to just return attrs but the problem persists.
Edit for models:
class Ingredient(models.Model):
item = models.ForeignKey(Item, on_delete=models.CASCADE)
amount = models.IntegerField()
def __str__(self):
return self.item.name + '(' + str(self.amount) + ')'
class Recipe(models.Model):
item = models.OneToOneField(Item, related_name='recipe', on_delete=models.CASCADE)
amount = models.IntegerField(default=1)
ingredients = models.ManyToManyField(Ingredient)
station = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='as_station')
def __str__(self):
return 'Recipe: ' + str(self.item)