0

Problem

I want to create Student With Address. How can I write REST API in Django for same.

Address & Student

class Address(models.Model):
    address = models.CharField(max_length=100, null=False, blank=False)
    land_mark = models.CharField(max_length=100, null=True, blank=True)
    city = models.CharField(max_length=100, null=True, blank=True)
    state = models.CharField(max_length=100, null=True, blank=True)
    pin_code = models.CharField(max_length=100, null=True, blank=True)
    latitude = models.FloatField(default=0.0)
    longitude = models.FloatField(default=0.0)
    geo_code = models.CharField(max_length=100, null=True, blank=True)
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, 
                                    null=True)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

 class Student(models.Model):
    name = model.CharField(max_length=100, null=False, blank=False)
    address = GenericRelation(Address)
    def __str__(self):
        return self.name

Serializers

class AddressSerializer(serializers.ModelSerializer):
    class Meta:
        model = Address
        fields = "__all__"


 class StuddentSerializer(serializers.ModelSerializer):
       class Meta:
            model = Student
            fields = "__all__"

API View

class AddressApiView(ListCreateAPIView):
    queryset = Address.objects.all()
    serializer_class = AddressSerializer

 class StudentApiView(ListCreateAPIView):
    queryset = Student.objects.all()
    serializer_class = StuddentSerializer

How do I get my create/view student?

Emma
  • 27,428
  • 11
  • 44
  • 69

1 Answers1

0

You can try with third-party app rest-framework-generic-relation link

Shakil
  • 4,520
  • 3
  • 26
  • 36
  • ya I tried but i want to create api for student not address like mentioned in =https://github.com/Ian-Foote/rest-framework-generic-relations example i want to create book or notes not taggs – Gaurav Bole Mar 08 '19 at 13:11
  • @GauravBole sorry buddy, i don't get your point properly. I have an intention that you may looking for a `moneyTomoney` or `foreignkey` relationship between these model, not generic-relation. As there is no multiple foreign-key present in Student model, What is you intention to do with this generic-relation. – Shakil Mar 08 '19 at 16:20
  • ya right @shakil I got your point and i changed generic foreign key to normal foreign key now solved a problem Thank. – Gaurav Bole Mar 09 '19 at 05:28