How to merge multiple models in serializer/view Django REST Framework?


born

I'm a newbie, please don't throw me slippers. The example is degenerate, but... there is a post model with text and owner. Each post is associated with its address, so the coordinates of the post are stored in a separate table. At this stage I can create a post with coordinates by overriding the create() method.

# models.py

    User = get_user_model()
    class Post(models.Model):
        owner = models.ForeignKey(User, on_delete=models.CASCADE)
        description = models.TextField(null=False, blank=True)
    
    
    class Address(models.Model):
        post = models.OneToOneField(Post, on_delete=models.CASCADE)
        lat = models.FloatField('Latitude', blank=True, null=True)
        lng = models.FloatField('Longitude', blank=True, null=True)

# serializer.py

    class AddressDetailSerializer(serializers.ModelSerializer):
        class Meta:
            model = Address
            fields = [
                'lat',
                'lng',
            ]
    
    
    class PostDetailSerializer(serializers.ModelSerializer):
        owner = serializers.HiddenField(default=serializers.CurrentUserDefault())
        addr_point = AddressDetailSerializer(many=False)
    
        class Meta:
            model = Post
            fields = [
                'id',
                'description',
                'owner',
                'addr_point',
            ]
    
        def create(self, validated_data):
            addr_point_data = validated_data.pop('addr_point')
            post = Post.objects.create(**validated_data)
            Address.objects.create(post=post, **addr_point_data)
            return post
# views.py

    class PostCreateView(generics.CreateAPIView):
        queryset = Post.objects.all()
        serializer_class = PostDetailSerializer

Now, I am completely clueless on how to display information about each post in the following format:

{
"owner": "admin"
"description": "blablabla",
"addr_point": {
"lat": 123,
"lng": 123
}
}

None of my serializer/view variants work or output the coordinate field.

UPD: For example, I use the following view to get information about some posts:

# view.py    
class PostDetailView(generics.RetrieveUpdateDestroyAPIView):
        serializer_class = PostDetailSerializer
        queryset = Post.objects.all()

But I get AttributeError: 'Post' object has no attribute 'addr_point'.

I'll be happy to get tips on which direction to move!

Kyle

When you try to retrieve an Postinstance using it PostDetailSerializer, it will look for the properties listed in PostDetailSerializer.Meta.fields.

So, in addr_pointaccess that doesn't exist in the model post.addr_point.

I suggest some changes:

# models.py
class Address(models.Model):
    post = models.OneToOneField(Post, on_delete=models.CASCADE, related_name="address")
    lat = models.FloatField('Latitude', blank=True, null=True)
    lng = models.FloatField('Longitude', blank=True, null=True)

# serializers.py
class PostDetailSerializer(serializers.ModelSerializer):
    owner = serializers.HiddenField(default=serializers.CurrentUserDefault())
    address = AddressDetailSerializer(many=False)

        class Meta:
            model = Post
            fields = [
                'id',
                'description',
                'owner',
                'address',
            ]
  • In the Address.postfield, we added the related_nameparameter, so we can access the reverse relationship with the specified string. In this case, we can access the post's address by accessing it post.address.
  • in PostDetailSerializerus addr_pointbecame address. postThis way, when the instance is serialized , post.addressit actually exists.

Related


Multiple models in Django Rest Framework?

Coderaemon: I am using Django Rest Framework . I want to serialize multiple models and send as response. Currently, only one model can be sent per view (as CartViewshown below, only Cart objects are sent). The following models (unrelated) can be there. class S

Multiple models in Django Rest Framework?

Coderaemon: I am using Django Rest Framework . I want to serialize multiple models and send as response. Currently, only one model can be sent per view (as CartViewshown below, only Cart objects are sent). The following models (unrelated) can be there. class S

Multiple models in Django Rest Framework?

Coderaemon I am using Django Rest Framework . I want to serialize multiple models and send as response. Currently I can only send one model per view (as CartViewbelow, only the Cart object). The following models (unrelated) can be there. class Ship_address(mod

Multiple models in Django Rest Framework?

Coderaemon: I am using Django Rest Framework . I want to serialize multiple models and send as response. Currently, only one model can be sent per view (as CartViewshown below, only Cart objects are sent). The following models (unrelated) can be there. class S

django rest framework nested fields with multiple models

Momokjaaaaa This is django and django rest framework. I have 2 models: User and Phone. first question: I want to be able to update user data (email) as well as phone data (phone number) in 1 api update response. Phone numbers can be 0 or many. Well, it's actua

Django Rest Framework, querying with multiple models

Ben2pop I'm very new to using REST frameworks and I didn't find in tutorials how to achieve what I'm looking for; In my serialiser.py I have a class for serializing MyUser model class MyUserSerializer(ModelSerializer): class Meta: model = MyUser

django rest framework nested fields with multiple models

Momokjaaaaa This is django and django rest framework. I have 2 models: User and Phone. first question: I want to be able to update user data (email) as well as phone data (phone number) in 1 api update response. Phone numbers can be 0 or many. Well, it's actua

Search tables for multiple models in Django Rest Framework

DjangoNoob I have 3 tables PC(ID, PcNAME, Brand) , CellPhoness(ID, CellPhoneName, Brand) , Printers(ID, PrinterName, Brand) . There is no relationship between these three tables. I want to run a query where the user can enter a search string and the program wi

django rest framework nested fields with multiple models

Momokjaaaaa This is django and django rest framework. I have 2 models: User and Phone. first question: I want to be able to update user data (email) as well as phone data (phone number) in 1 api update response. Phone numbers can be 0 or many. Well, it's actua

Django-Rest Framework multiple models

collet I'm starting to use Django Rest Framework and it's a great tool! Actually, I'm stuck in some simple puzzles, but have no way of figuring out how to do it...I have two models, CustomUser and Order. Here, CustomUser has 0 to many orders. I want to generat

django rest framework nested fields with multiple models

Momokjaaaaa This is django and django rest framework. I have 2 models: User and Phone. first question: I want to be able to update user data (email) as well as phone data (phone number) in 1 api update response. Phone numbers can be 0 or many. Well, it's actua

Search tables for multiple models in Django Rest Framework

DjangoNoob I have 3 tables PC(ID, PcNAME, Brand) , CellPhoness(ID, CellPhoneName, Brand) , Printers(ID, PrinterName, Brand) . There is no relationship between these three tables. I want to run a query where the user can enter a search string and the program wi

django rest framework nested fields with multiple models

Momokjaaaaa This is django and django rest framework. I have 2 models: User and Phone. first question: I want to be able to update user data (email) as well as phone data (phone number) in 1 api update response. Phone numbers can be 0 or many. Well, it's actua

How to validate models in Django Rest Framework?

Akaphenom I have a model which is essentially a single table with four lookup tables. One of the lookup tables is to specify the type. Depending on the type (there are four in total), the requirements for the fields vary. For example, if the type is "survey",

Django Rest Framework: No Models

Facebook facebook Rahul Nama to contact I am creating a REST API using DRF (Django Rest Framework). The API just takes the user's twitter handle and returns their twitter data. Here, I'm not using a model here because it's not required. Should I be using a ser

Django Rest Framework: No Models

Facebook facebook Rahul Nama to contact I am creating a REST API using DRF (Django Rest Framework). The API just takes the user's twitter handle and returns their twitter data. Here, I'm not using a model here because it's not required. Should I be using a ser

Django REST: Merge two models

Liu I'm just getting started with django rest framework, this may be an old question, but so far I haven't found any proper answer on SO. I want to add some extra profile fields to the existing user model provided by DRF. After reading the documentation, I cho

Return results from multiple models using Django REST Framework

aendrew : I have three models - Article, Author and Tweet. I eventually need to use the Django REST Framework to build a feed that aggregates all the objects into a reverse temporal feed using the Article and Tweet models. Any idea what I would do? I feel like

Return results from multiple models using Django REST Framework

Arndru I have three models - Article, Author and Tweet. I eventually need to construct a feed using Django REST Framework that aggregates all objects using the Article and Tweet models into one reverse chronological feed. Any idea what I would do? I feel like

Return results from multiple models using Django REST Framework

aendrew : I have three models - Article, Author and Tweet. I eventually need to use Django REST Framework to build a feed that aggregates all objects into a reverse temporal feed using Article and Tweet models. Any idea what I would do? I feel like I need to c