Please excuse the title. Im not quite sure how ask this question without just showing.
In django I have two models.
class people(models.Model):
name=models.TextField(max_length=100)
nickname=models.TextField(max_length=100)
class visits(models.Model):
person=models.OneToOneField(people)
visitdate=models.DateTimeField(auto_now=True)
and then a serializer for the restapi.
#serializers.py
class VisitsSerializer(serializers.ModelSerializer):
class Meta:
model = visits
fields=("id","person","date")
When the API returns the dictionary, it looks like this.
{id:1,person:1,visitdate:11/23/17}
Is there a way to make the API return the actual values that are associated with the person with id 1? like so.
{id:1,person:{id:1,name:foo,nickname:bar},visitdate:11/23/17}
Try creating a serializer class for People and then add this to your visit serializer:
people = PeopleSerializer(read_only = True)
then add it(people) to fields in the Meta class, and just a suggestion, try making it a foreign key instead of a OnetoOne Relationship
You can do that with nested relationship. Here is an example:
class PersonSerializer(serializers.ModelSerializer):
class Meta:
model = people
fields = ('name', 'nickname')
class VisitsSerializer(serializers.ModelSerializer):
person = PersonSerializer(read_only=True)
class Meta:
model = visits
fields = ("id", "person", "date")
Documentation on nested serializers is here.
The Corresponding Serializer would be as follows:
class PersonSerializer(serializers.ModelSerializer):
class Meta:
model = people
class VisitsSerializer(serializers.ModelSerializer):
person = serializers.SerializerMethodField()
class Meta:
model = visits
fields = ('id', 'person', 'date')
def get_person(self, obj):
return PersonSerializer(obj.person).data
Related
So, I have a weird legacy issue where I have one model "Data", and for serialization purposes I need to restructure the fields.
class Data(models.Model):
id ...
field_a
field_b
field_c
date
Then I have the serializers:
class DataInfoSerializer(ModelSerializer):
class Meta:
model = Data
fields = ['field_a', 'field_b', 'field_c']
class DataSerializer(ModelSerializer):
data_info = DataInfoSerializer(required=False, read_only=True)
class Meta:
model = Data
fields = ['id', 'date', 'data_info']
Now I somehow have to get DRF to use the same instance of Data that is passed into the "DataSerializer" to render the DataInfoSerializer.
Any ideas how to achieve this? Or a better way.
Use source='*' to pass the entire object to a field, including nested serializers. Docs
class DataSerializer(ModelSerializer):
data_info = DataInfoSerializer(required=False, read_only=True, source='*')
class Meta:
model = Data
fields = ['id', 'date', 'data_info']
This is just my curiosity but I will be very happy if anyone answers my question.
I am using Django Rest Framework but I'm a beginner. In serializers.py, I use ModelSerializer and "all" to fields attribute.
This is an example.
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = "__all__"
And then, I just thought
when don't we use "__all__" in serializers.py??
As long as we create models.py in advance, I think we usually use all fields in each Model.
I would like you to teach me when we omit specific fields that come from each Model.
Thank you.
So the second question is a bit harder to explain in a comment:
If we use some fields of all fields in Model, how do we store information of the rest of fields?
Various cases:
Fields with defaults:
class Log(models.Model):
message = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
class LogSerializer(serializers.ModelSerializer):
class Meta:
model = Log
fields = ('message',)
For autogenerated, think user profile models via the post_save signal or calculated fields:
class OrderLine(models.Model):
order = models.ForeignKey(Order)
name = models.CharField(max_length=200)
quantity = models.IntegerField()
price = models.DecimalField()
class OrderLineSerializer(serializers.ModelSerializer):
order = serializers.PrimaryKeyRelatedField()
product = serializers.IntegerField()
class Meta:
model = OrderLine
fields = ('quantity', 'product', 'order')
In this case, the product is a primary key for a product. The serializer will have a save method that looks up the product and put it's name and price on the OrderLine. This is standard practice as you cannot reference a product in your orders, else your orders would change if you change (the price of) your product.
And derived from request:
class BlogPost(models.Model):
author = models.ForeignKey(User)
post = models.TextField()
class BlogPostSerializer(serializers.ModelSerializer):
class Meta:
model = BlogPost
fields = ('post',)
def create(self, validated_data):
instance = BlogPost(**validated_data)
instance.author = self.context['request'].user
instance.save()
return instance
This is pretty much the common cases.
There are many cases, but I think the two main ones are:
When you don't want all fields to be returned by the serializer.
When you need some method of the serializer to know its fields. In such case, you should traverse fields array, but it doesn't work if you use __all__, only if you have an actual list of fields.
I feel like this is a super basic question but am having trouble finding the answer in the DRF docs.
Let's say I have a models.py set up like so:
#models.py
class Person(models.Model):
name = models.CharField(max_length=20)
address = models.CharField(max_length=20)
class House(models.Model):
name = models.CharField(max_length=20)
owner = models.ForeignKey(Person)
And I have a ModelSerializer set up like so:
#serializers.py
class House(serializers.ModelSerializer):
class Meta:
model = House
fields = '__all__'
What I want to do is to be able to POST new House objects but instead of having to supply the pk of the Person object, I want to be able to supply the name of the Person object.
E.g.
post = {'name': 'Blue House', 'owner': 'Timothy'}
The actual models I'm using have several ForeignKey fields so I want to know the most canonical way of doing this.
One solution may be to use a SlugRelatedField
#serializers.py
class House(serializers.ModelSerializer):
owner = serializers.SlugRelatedField(
slug_field="name", queryset=Person.objects.all(),
)
class Meta:
model = House
fields = '__all__'
This will also change the representation of your serializer though, so it will display the Person's name when you render it. If you need to render the Person's primary key then you could either override the House serializers to_representation() method, or you could implement a small custom serializer field by inheriting SlugRelatedField and overriding to_representation() on that instead.
Change your serializer as below by overriding the create() method
class House(serializers.ModelSerializer):
owner = serializers.CharField()
class Meta:
model = House
fields = '__all__'
def create(self, validated_data):
owner = validated_data['owner']
person_instance = Person.objects.get(owner=owner)
return House.objects.create(owner=person_instance, **validated_data)
I have a Cart model and a CartItem model. The CartItem model has a ForeignKey to the Cart model.
Using Django Rest Framework I have a view where the API user can display the Cart, and obviously then I want to include the CartItem in the respone.
I set up my Serializer like this:
class CartSerializer(serializers.ModelSerializer):
user = UserSerializer(read_only=True)
cartitem_set = CartItemSerializer(read_only=True)
class Meta:
model = Cart
depth = 1
fields = (
'id',
'user',
'date_created',
'voucher',
'carrier',
'currency',
'cartitem_set',
)
My problem is the second line, cartitem_set = CartItemSerializer(read_only=True).
I get AttributeErrors saying 'RelatedManager' object has no attribute 'product'. ('product' is a field in the CartItem model. If I exclude product from the CartItemSerializer I just get a new AttributeError with the next field and so on. No matter if I only leave 1 or all fields in the Serializer, I will get a error.
My guess is that for some reason Django REST Framework does not support adding Serializers to reverse relationships like this. Am I wrong? How should I do this?
PS
The reason why I want to use the CartItemSerializer() is because I want to have control of what is displayed in the response.
Ahmed Hosny was correct in his answer. It required the many parameter to be set to True to work.
So final version of the CartSerializer looked like this:
class CartSerializer(serializers.ModelSerializer):
cartitem_set = CartItemSerializer(read_only=True, many=True) # many=True is required
class Meta:
model = Cart
depth = 1
fields = (
'id',
'date_created',
'voucher',
'carrier',
'currency',
'cartitem_set',
)
It's important to define a related name in your models, and to use that related name in the serializer relationship:
class Cart(models.Model):
name = models.CharField(max_length=500)
class CartItem(models.Model):
cart = models.ForeignKey(Cart, related_name='cart_items')
items = models.IntegerField()
Then in your serializer definition you use those exact names:
class CartSerializer(serializers.ModelSerializer):
cart_items = CartItemSerializer(read_only=True)
class Meta:
model = Cart
fields = ('name', 'cart_items',)
It would be wise to share your whole code, that is model and serializers classes. However, perhaps this can help debug your error,
My serializer classes
class CartItemSerializer(serializers.ModelSerializer):
class Meta:
model = CartItem
fields = ('id')
class CartSerializer(serializers.ModelSerializer):
#take note of the spelling of the defined var
_cartItems = CartItemSerializer()
class Meta:
model = Cart
fields = ('id','_cartItems')
Now for the Models
class CartItem(models.Model):
_cartItems = models.ForeignKey(Subject, on_delete=models.PROTECT)
#Protect Forbids the deletion of the referenced object. To delete it you will have to delete all objects that reference it manually. SQL equivalent: RESTRICT.
class Meta:
ordering = ('id',)
class Cart(models.Model):
class Meta:
ordering = ('id',)
For a detailed overview of relationships in django-rest-framework, please refer their official documentation
Let's say I have a model name Book. I have two views(list and detail)
models.py
class Book(models.Model):
name = models.CharField(max_length=100)
author = models.CharField(max_length=100)
publishdate = models.DateTimeField()
serializers.py
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
If I'm going to use this serializer in my list view and detail view. Can I set the return field? Example : list view only return name list only and detail view will return name, author, publishdate field.
Or do I have to create new serializer and insert fields in Class Meta on both class?
If you need different representations for list and detail views you should define seperate serializers for each. For example...
class DetailBookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('name', 'author', 'publishdate')
class ListBookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('name',)
Then make sure to set the serializer_class attribute as appropriate on each view.