I have models:
class CommonEditor(models.Model):
def __str__(self):
return 'Common Atributes Mask'
class Color(models.Model):
name = models.CharField(max_length=25)
editor = models.ForeignKey(CommonEditor, on_delete=models.PROTECT, null=True)
So I make serialization this way:
class ColorSerializer(serializers.ModelSerializer):
class Meta:
model = Color
fields = '__all__'
class CommonAttributesSerializer(serializers.ModelSerializer):
color = ColorSerializer(many=True, read_only=True)
class Meta:
model = CommonEditor
fields = ('pk', 'color')
And then view:
class CommonAttributeAPIView(generics.ListCreateAPIView):
serializer_class = CommonAttributesSerializer
queryset = CommonEditor.objects.all()
I get only pk of my CommonEditor Model. Why can't i get the full Atributes Mask and how can I fix it? Big thanks!
Default name for reverse foreign key relation is modelname_set or in your case color_set. So try to rename color field to color_set:
class CommonAttributesSerializer(serializers.ModelSerializer):
color_set = ColorSerializer(many=True, read_only=True)
class Meta:
model = CommonEditor
fields = ('pk', 'color_set')
This can also be achieved via SerializerMethodField and can be seen as follow:
class CommonAttributesSerializer(serializers.ModelSerializer):
color = serializers.SerializerMethodField()
class Meta:
model = CommonEditor
fields = ('pk', 'color')
def get_color(self, common_editor):
return ColorSerializer(common_editor.color_set.all(), many=True).data
Documentation: http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield
The CommonAttributesSerializer search for a color attribute in CommonEditor's instance, but it couldn't find. In DRF serializer, a parameter called source will says explicitly where to look for the data. So , change the serializer as below:
class CommonAttributesSerializer(serializers.ModelSerializer):
color = ColorSerializer(many=True, read_only=True, <b>source='color_set'</b>)
class Meta:
model = CommonEditor
fields = ('pk', 'color')
Reference : DRF Fields -source
Related
I use django rest in my project and until now for list of objects I used ListSerializer, when I needed to have min length and max length of list I googled and reached to ListField.
Before that my code worked fined without any error and misbehavior. Now I use ListField for my list field serializer, But I didn't get when to use ListSerializer? Can someone explain the difference between ListSerializer and FieldSerializer?
My sample code with ListSerializer:
tags = serializers.ListSerializer(child=serializers.CharField(allow_blank=False), required=False)
My sample code with ListField:
open_hour = serializers.ListField(child=serializers.DictField(), max_length=7, min_length=7)
Disclaimer: This answer is not complete
Can someone explain the difference between ListSerializer and
FieldSerializer?
I assume the question is difference between serializers.ListSerializer and serializers.ListField
Suppose we have two models as
class Musician(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
instrument = models.CharField(max_length=100)
def __str__(self):
return f'{self.first_name} {self.last_name}'
class Album(models.Model):
artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
release_date = models.DateField()
num_stars = models.IntegerField()
def __str__(self):
return f'{self.name} : {self.artist}'
and serializer as
class AlbumSerializer(serializers.ModelSerializer):
artist = serializers.StringRelatedField()
class Meta:
fields = '__all__'
model = Album
class MusicianSerializer(serializers.ModelSerializer):
AlbumSerializer(many=True, source='album_set')
class Meta:
fields = '__all__'
model = Musician
ListSerializer
As stated in official DRF doc
When a serializer is instantiated and many=True is passed, a
ListSerializer instance will be created. The serializer class then
becomes a child of the parent ListSerializer
For example, we could re-write the MusicianSerializer with ListSerializer as
class MusicianSerializer(serializers.ModelSerializer):
albums = serializers.ListSerializer(child=AlbumSerializer(), source='album_set')
class Meta:
fields = '__all__'
model = Musician
it would produce the results same as before. But, if we are trying to use ListField instead of ListSerializer It will raise an error
'RelatedManager' object is not iterable
When I checked the source code, I found that both ListSerializer and ListField are inherited from the same class (parent and grand parent are same)
I ran into this same problem and I believe I found a solution!
The trick is you need to create a new Serializer that inherits the ListSerializer class and override the to_representation() method to output your desired format.
If you look at the DRF source code for ListSerializer you can see the default to_representation() method looks like the following...
def to_representation(self, data):
"""
List of object instances -> List of dicts of primitive datatypes.
"""
# Dealing with nested relationships, data can be a Manager,
# so, first get a queryset from the Manager if needed
iterable = data.all() if isinstance(data, models.Manager) else data
return [
self.child.to_representation(item) for item in iterable
]
Example
models
class Musician(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
instrument = models.CharField(max_length=100)
def __str__(self):
return f'{self.first_name} {self.last_name}'
class Album(models.Model):
artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
release_date = models.DateField()
num_stars = models.IntegerField()
def __str__(self):
return f'{self.name} : {self.artist}'
serializers
class AlbumSerializer(serializers.ModelSerializer):
artist = serializers.StringRelatedField()
class Meta:
fields = '__all__'
model = Album
class AlbumKeyValueSerializer(serializers.ListSerializer):
def to_representation(self, data):
reaction_count_set = {}
for item in data.all():
reaction_count_set[item.name] = item.artist
return reaction_count_set
class MusicianSerializer(serializers.ModelSerializer):
AlbumKeyValueSerializer(child=AlbumSerializer(), source='album_set')
class Meta:
fields = '__all__'
model = Musician
models.py
class Category(models.Model):
name = models.CharField(max_length=128)
class Product(models.Model):
category = models.ManyToManyField(Category, related_name="category")
name = models.CharField(max_length=128)
class ProductVariation(models.Model):
product = models.ForeignKey(Product, related_name="product")
name = models.CharField(max_length=128)
serializers.py
class ProductVariantSerializer(serializers.HyperlinkedModelSerializer)
class Meta:
model = ProductVariation
fields = (
"name",
)
class CategoryDetailSerializer(serializers.Modelserializer):
product_variant = PromotionVariantSerializer(many=True)
class Meta:
model = Category
fields =(
"name",
"product_variant" #how can i do this
)
here i want to list all the product variant that belongs to the category.
can i do this way or i want to write methods to get the product variant details
You may need to write serializers for Product and ProductVariation models. You can't display the ProductVariation objects right in the Category model serializer, as there is no direct relation between Category and ProductVariation models. But you could try may be using separate nested serializers for Product and ProductVariation models.
class ProductVariantSerializer(serializers.ModelSerializer):
class Meta:
model = ProductVariation
fields = ("name", )
class ProductSerializer(serializers.ModelSerializer):
variants = ProductVariantSerializer(source='product', many=True, read_only=True)
class Meta:
model = Product
fields = ('name', 'variants')
class CategorySerializer(serializers.ModelSerializer):
products = ProductSerializer(source='category', many=True, read_only=True)
class Meta:
model = Category
fields = ('name', 'products')
You could use the CategorySerializer for nested relationships.
I'm using the DjangoRest Framework with 2 models DeviceType and Channel. Now Channel has a ForeignKeyField pointing to a DeviceType. No problem so far.
But now I don't want all DeviceTypes to be selectable when adding or editing a Channel but only the DeviceTypes that have their usesChannels field set to True.
So I used the limit_Choices_to attribute but somehow that doesn't seem to work. No matter what I do, I alway get a list with all DeviceTypes including the ones with usesChannels set to False
This is my code:
models.py
class DeviceType(models.Model):
name = models.CharField(max_length=30)
usesChannels = models.BooleanField()
def __str__(self):
return '%s' % (self.name)
class Channel(models.Model):
type = models.ForeignKey(DeviceType, limit_choices_to={'usesChannels': True})
name = models.CharField(max_length=30)
channelNr = models.IntegerField()
serializers.py
class DeviceTypeSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = DeviceType
fields = ('url', 'name', 'usesChannels')
class ChannelSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Channel
flieds = ('url', 'type', 'name', 'channelNr')
I used the ForeignKey.limit_choices_to example from This link
Edit: I use the DRF browsable API to add, edit and remove data.
Answer: After struggling with this for a few days I found a working solution:
models.py
class DeviceType(models.Model):
name = models.CharField(max_length=30)
usesChannels = models.BooleanField()
def __str__(self):
return '%s' % (self.name)
class Channel(models.Model):
type = models.ForeignKey(DeviceType)
name = models.CharField(max_length=30)
channelNr = models.IntegerField()
serializers.py
class DeviceTypeSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = DeviceType
fields = ('url', 'name', 'usesChannels')
class ChannelSerializer(serializers.HyperlinkedModelSerializer):
type = serializers.PrimaryKeyRelatedField(queryset=DeviceType.objects.filter(usesChannels=True))
class Meta:
model = Channel
flieds = ('url', 'type', 'name', 'channelNr')
Edit: For completeness I'll add the views too
Views.py:
class DeviceTypeViewSet(viewsets.ModelViewSet):
queryset = DeviceType.objects.all()
serializer_class = DeviceTypeSerializer
class ChannelViewSet(viewsets.ModelViewSet):
queryset = Channel.objects.all()
serializer_class = ChannelSerializer
Ran into this problem today. I believe it does indeed completely ignore the attribute; at least I couldn't find any reference to it in DRF's code.
So I "solved" the problem by adding Serializer.__init__ constructor and within it the following function / code:
class MySerializer(Serializers.Serializer):
def __init__(self, *args, **kwargs):
...
def limit_choices_to(field_name):
fld = self.fields[field_name]
fld.queryset = fld.queryset.filter(**Flight._meta.get_field(field_name).get_limit_choices_to())
limit_choices_to('my_field')
I want to fetch the foreign key values in PUT and GET but while using the many=True I am getting error TypeError object is not iterable.
Here are following the my snippets.
I have two models called MasterStatus and MasterType. In MasterType I have foreign key values of MasterStatus.
models.py
class MasterType(models.Model):
id = models.BigIntegerField(primary_key=True)
type_name = models.CharField(max_length=255, blank=True, null=True)
fk_status = models.ForeignKey(MasterStatus)
def __unicode__(self):
return u'%s' % (self.type_name)
class Meta:
managed = False
db_table = 'master_type'
In serializer I am using the many=True to get the nested values of foreignkey. Here I have used PrimaryKeyRelatedField serializer.
serializer.py
class MasterTypeSerializer(serializers.HyperlinkedModelSerializer):
fk_status = serializers.PrimaryKeyRelatedField(queryset=MasterStatus.objects.all(),many=True)
class Meta:
model = MasterType
fields = ('id', 'type_name', 'fk_status', 'last_modified_date', 'last_modified_by')
depth = 2
ForeignKey links to a single MasterStatus instance, therefore it is not many.
Your serializers should look something like this:
class MasterTypeSerializer(serializers.HyperlinkedModelSerializer):
fk_status = serializers.PrimaryKeyRelatedField(
queryset=MasterStatus.objects.all())
class Meta:
model = MasterRepaymentType
class MasterStatusSerializer(serializers.HyperlinkedModelSerializer):
fk_type = serializers.PrimaryKeyRelatedField(
queryset= MasterRepaymentType.objects.all(), many=True)
class Meta:
model = MasterStatus
Note that many is used on the fk_type field as a MasterStatus has many MasterRepaymentType.
Hope this helps.
I have models like this:
class Car(models.Model):
name = models.CharField(max_length=255)
class CarImage(models.Model):
car = models.ForeignKey(Car, related_name='photos')
photo = models.ImageField(upload_to='car/')
For the serializer I have:
class CarImageSerializer(serializer.ModelSerializer):
class Meta:
model = CarImage
class CarSerializer(serializer.ModelSerializer):
photos = CarImageSerializer()
class Meta:
model = Car
fields = ('id', 'name', 'photos',)
When the web interface for CarSerializer loads I get non_field_errors on the photos field by default. Is this kind of thing supported by DRF? If not what's the best way to do this?
P.S I am using generic CreateAPIView
Using docs you should do this from another way:
class CarSerializer(serializer.ModelSerializer):
photos = serializers.RelatedField(many=True)
class Meta:
model = Car
fields = ('id', 'name', 'photos',)
Maybe you can try this:
serializers.py
class CarImageSerializer(serializers.ModelSerializer):
class Meta:
model = CarImage
class CarSerializer(serializers.HyperlinkedModelSerializer):
photos = serializers.HyperlinkedRelatedField(many=True,
view_name='carimage-list')
class Meta:
model = Car
fields = ('id', 'name', 'photos',)
views.py
class CarImageList(ListCreateAPIView):
queryset = CarImage.objects.all()
serializer_class = CarImageSerializer
class CarList(ListCreateAPIView):
queryset = Car.objects.all()
serializer_class = CarSerializer
urls.py
url(r'^carimage/$', CarImageList.as_view(), name='carimage-list'),
url(r'^car/$', CarList.as_view(), name='car-list'),
You should take care about all needed imports. No guarantee, but you could give it a try.