It´s a requirement of the project to start from an existing database. In which there are tables with compound keys. When generating the models from this database, a field was left as the primary key, and a constraint unique with both fields that previously formed the composite key.
An example follows:
models.py
class Preciosventalista(models.Model):
idlistaprecio = models.OneToOneField(Listasprecios, models.DO_NOTHING, db_column='idlistaprecio', primary_key=True)
idarticu = models.ForeignKey(Articulos, models.DO_NOTHING, db_column='idarticu')
porcendescue = models.DecimalField(max_digits=6, decimal_places=2)
cohefi = models.DecimalField(max_digits=10, decimal_places=4)
precioneto = models.DecimalField(max_digits=10, decimal_places=4)
precioventa = models.DecimalField(max_digits=10, decimal_places=2)
class Meta:
managed = True
db_table = 'preciosventalista'
unique_together = (('idlistaprecio', 'idarticu'),)
serializers.py
class ArticulosSerializer(serializers.ModelSerializer):
class Meta:
model = Articulos
fields='__all__'
class PreciosVentaListaSerializer(serializers.ModelSerializer):
articulo = ArticulosSerializer(source='idarticu', read_only=True)
class Meta:
model = Preciosventalista
fields='__all__'
apiviews.py
class PreciosVentaListaList(generics.ListCreateAPIView):
queryset = Preciosventalista.objects.all()
serializer_class = PreciosVentaListaSerializer
class PreciosVentaListaDetalle(generics.RetrieveDestroyAPIView):
queryset = Preciosventalista.objects.all()
serializer_class = PreciosVentaListaSerializer
urls.py
urlpatterns = [
path('v1/preciosventalista/', PreciosVentaListaList.as_view(), name='preciosventalista_list'),
path('v1/preciosventalista/<int:pk>', PreciosVentaListaDetalle.as_view(), name='preciosventalista_detalle')
]
The error when calling the service ( /api/v1/preciosventalista/1 ) from postman is:
MultipleObjectsReturned at /api/v1/preciosventalista/1 get() returned more than one Preciosventalista -- it returned 75!
I couldn´t get my service to return a set of instances or to be able to filter through both fields (idlistaprice, idarticu) to return a single instance. I have tried the following without results:
apiviews.py
class PreciosVentaListaDetalle(generics.RetrieveDestroyAPIView):
queryset = Preciosventalista.objects.all()
serializer_class = PreciosVentaListaSerializer
def list(self, request):
queryset = self.get_queryset()
serializer = UserSerializer(queryset, many = true)
return Response(serializer.data)
If I am making beginner mistakes I apologize but I have been working with the framework for a short time, I would appreciate any help or guidance that can help me solve the problem. Thank you so much!