我发现很难找到解决问题的方法,我正在尝试这样做:
/127.0.0.1:8080/companies/1/cars/1
在我的CompanyViewSet中,我可以进入名为car的函数,汽车实例恰到好处..但我无法将其放入序列化程序并显示信息
我有以下代码:
模型:
class Car(models.Model):
name = models.CharField(max_length=255)
price = models.IntegerField(default=0)
created = models.DateTimeField(auto_now=True)
companies = models.ManyToManyField('Company', related_name='CarBelongToCompny', through='CarBelongToCompny')
objects = PassThroughManager.for_queryset_class(CarQueries)()
def __unicode__(self):
return self.name
def save(self,*args,**kwargs):
super(Car, self).save(*args, **kwargs)
return self
class Company(models.Model):
cities = (
('rishon leziyyon', 'rishon leziyyon'),
('tel aviv', 'tel aviv'),
('beer sheva', 'beer sheva'),
('eilat', 'eilat'),
('kefar saba', 'kefar saba'),
)
name = models.CharField(max_length=255)
city = models.CharField(max_length=255,
choices=cities,)
phone_number = models.IntegerField(default=0)
is_active = models.BooleanField(default=True)
cars = models.ManyToManyField('Car', related_name='CarBelongToCompny', through='CarBelongToCompny')
objects = PassThroughManager.for_queryset_class(ComapniesQuerySet)()
def __unicode__(self):
return self.name
def save(self,*args,**kwargs):
super(Company, self).save(*args, **kwargs)
return self
class CarBelongToCompny(models.Model):
price_at_company = models.IntegerField(default=0)
company = models.ForeignKey(Company, related_name='companyName')
car = models.ForeignKey(Car, related_name='carName')
objects = PassThroughManager.for_queryset_class(CarBelongCompanyQueries)()
def __unicode__(self):
return self.car.name + " " + self.company.name + " " + str(self.price_at_company)
串行器:
class CompanySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.Company
class PriceListSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.CarBelongToCompny
class CarSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.Car
的观点:
class CarViewSet(NestedViewSetMixin, viewsets.ModelViewSet):
queryset = Car.objects.all()
serializer_class = CarSerializer
class CompanyViewSet(NestedViewSetMixin, viewsets.ModelViewSet):
queryset = Company.objects.all()
serializer_class = CompanySerializer
@link()
def cars(self, request, pk):
cars = CarBelongToCompny.objects.filter(company__id=pk)
serializer = PriceListSerializer(cars)
return Response(serializer.data)
class PriceListViewSet(NestedViewSetMixin, viewsets.ModelViewSet):
queryset = CarBelongToCompny.objects.all()
model = models.CarBelongToCompny
当我进入公司时/ 1我希望能够添加汽车并查看该公司所有要求的汽车,是否可能?
答案 0 :(得分:1)
class CompanyViewSet(NestedViewSetMixin, viewsets.ModelViewSet):
queryset = Company.objects.all()
serializer_class = CompanySerializer
@action(methods=['GET', 'POST'])
def cars(self, request, pk):
if request.method== "GET":
cars = CarBelongToCompny.objects.filter(company__id=pk)
serializer = PriceListSerializer(cars)
return Response(serializer.data)
if request.method== "POST":
################
# create logic