Home > Blockchain >  Django ViewSet, get data from model without foreign key
Django ViewSet, get data from model without foreign key

Time:01-20

My Models

def ModelA(models.Model):
    id = models.CharField(primary_key=True, max_length=50)
    val_a = models.CharField(db_index=True, max_length=100)
    val_b = models.CharField(db_index=True, max_length=100)
    modelB = models.ForeignKey(modelB, on_delete=models.CASCADE, db_constraint=False)

def ModelB(models.Model):
    id = models.CharField(primary_key=True, max_length=50)
    val_c = models.CharField(db_index=True, max_length=100)
    val_d = models.CharField(db_index=True, max_length=100)

def ModelC(PostgresModel):
    id = models.CharField(primary_key=True, max_length=50)
    val_e = models.CharField(db_index=True, max_length=100)
    modelB = models.OneToOneField(ModelB, on_delete=models.CASCADE, null=False, blank=False)

My ViewSet

class ModelAViewSet(ListDataResponseMixin, APIKeyViewSet):
    endpoint_permissions = [APILicenseKeyPermission.Codes.A]

    queryset = ModelA.objects.all()
    serializer_class = ModelASerializer
    filterset_class = ModelAFilter
    filter_backends = [DjangoFilterBackend]

My Serializer

class ModelASerializer(serializers.ModelSerializer):
    class Meta:
        model = ModelA
        fields = (
            "id",
            "val_a",
            "val_b"
        )

When querying ModelA I would like to get val_e from ModelC. I am learning django, and previously when I needed to do something like this, I would use select_related, however, since there is no clear path from ModelA -> ModelC using foreign keys, I am not sure how to proceed. (My base models cannot change). How would I modify my ViewSet to include the needed ModelC data in my queryset? And then for my ModelASerializer I would like to just be able to add in val_e.

CodePudding user response:

You can simply use a CharField, like this:

class ModelASerializer(serializers.ModelSerializer):
    val_e = serializers.CharField(source='modelB.modelc.val_e')
    class Meta:
        model = ModelA
        fields = (
            "id",
            "val_a",
            "val_b",
            "val_e"
        )

This is possible because ModelA has a ForeignKey to ModelB and ModelB has One To One relation to ModelC. More information on source can be found in documentation.

  • Related