使用reactjs从api中获取外键对象

时间:2016-02-27 01:03:07

标签: python django api reactjs tastypie

我很困惑,我很难继续我的项目。我正在开发租赁系统应用程序,用户可以在其中注册他们的空间(包括所有者名称,列表名称,电子邮件,摘要,他们房间的多个图像等)。我已经为此创建了两个表。一个用于租赁详细信息,另一个用于多个图像用于租赁。 我为两者创建了一个api资源。我也可以将数据保存到我的数据库中。我成功使用reactjs和tastpyie获取租赁详细信息,但我无法获取与该租赁相关联的图像。我应该为此做什么?

Models.py

class Rental(models.Model):
    ownerName = models.CharField(_("Owner's Name"),max_length=255, blank=True,null=True,
        help_text=_("Owner's Full Name"))
    listingName =  models.CharField(_("Lisitng Name"), max_length=255, blank=False,null=True,
        help_text=_("Title of the rental space"))
    summary = models.TextField(max_length=500, blank=True,null=True,help_text=_("Description of the rental space"))
    room = models.PositiveIntegerField(_("No of Rooms"), blank=False, null=True,
        help_text=_("Number of bedrooms available"))
    price = models.PositiveIntegerField(blank=False,null=True,
        help_text=_("Rental price of the space per month"))

    def save_images(self, images,instance):
        for image in images:
            GalleryImage.objects.create(image=image, rental=instance)


    def __str__(self):
        return self.listingName


class GalleryImage(models.Model):
    rental = models.ForeignKey('Rental',on_delete=models.CASCADE,blank=True,null=True,
                                verbose_name=_('Rental'), related_name="gallery")
    image = models.FileField(blank=True,upload_to='upload/',null=True)

api.py

class MultipartResource(object):
    def deserialize(self, request, data, format=None):
        if not format:
            format = request.META.get('CONTENT_TYPE', 'application/json')
        if format == 'application/x-www-form-urlencoded':
            return request.POST
        if format.startswith('multipart'):
            data = request.POST.copy()
            data.update(request.FILES)
            return data
        return super(MultipartResource, self).deserialize(request, data, format)

    def put_detail(self, request, **kwargs):
        if request.META.get('CONTENT_TYPE').startswith('multipart') and \
                not hasattr(request, '_body'):
            request._body = ''
        return super(MultipartResource,self).put_detail(request,**kwargs)

    def patch_detail(self, request, **kwargs):
        if request.META.get('CONTENT_TYPE', '').startswith('multipart/form-data') and not hasattr(request, '_body'):
             request._body = ''
        return super(MultipartResource, self).patch_detail(request, **kwargs)

class RentalResource(MultipartResource,ModelResource):
    class Meta:
        queryset = Rental.objects.all()
        resource_name = 'rental'
        allowed_methods = ['get', 'post','put']
        fields = ['listingName','ownerName','room','price','summary']
        filtering = { "property" : ALL , "room":ALL,"price":ALL}
        authorization = DjangoAuthorization()

class GalleryImageResource(ModelResource):
    rental = fields.ForeignKey(RentalResource, 'rental')
    class Meta:
        queryset = GalleryImage.objects.all()
        resource_name = 'gallery'
        allowed_methods = ['get','post','put']
        authorization = DjangoAuthorization()

反应用于获取数据的代码

export default class RoomList extends React.Component{
    constructor(props){
        super(props);
        this.state = { rooms: [] }
    }

    componentDidMount(){
        console.log('componentDidMount');
        this.loadRoomFromServer();
    }

    loadRoomFromServer(){
        $.ajax({
            url:'/api/v1/rental/',
            dataType:'json',
            success: (data) => {
                console.log('data',data);
                this.setState({rooms: data.objects});
                console.log('success');
              },
              error: (xhr, status, err) => {
                console.error(url, status, err.toString());
              }
            });
    }

    render(){
        console.log('rooms',this.state.rooms);
        let listOfRoom = this.state.rooms.map((room,id)=>{
            return(
                    <Rooms key={id} name={room.listingName} price={room.price} number={room.room} />
                )
        });
        console.log('listOfRoom',listOfRoom);
        return(
                <div className="container-fluid">
                    <div className="row">
                            { listOfRoom }
                    </div>
                </div>
            )
    }
}

class Rooms extends React.Component{
    render(){
        return(
                <div className="col-md-4">
                    <h2>{this.props.name}</h2>
                    <p>{this.props.price}</p>
                    <p>{this.props.number}</p>
                </div>
            )
    }
}

由于网址与租借和图库不同,我现在如何获取与该租金相关的图片? 我们将不胜感激。 感谢

1 个答案:

答案 0 :(得分:1)

请参阅:https://django-tastypie.readthedocs.org/en/latest/resources.html?highlight=relationships#reverse-relationships

Tastypie不会自动添加关系字段,您需要手动执行这些操作。

如果您想点击租赁端点并获取相关的图库资源,请执行以下操作:

class RentalResource(MultipartResource,ModelResource):
    gallery = fields.ToMany('path.to.GalleryImageResource', 'gallery', related_name='rental', full=True)

    class Meta:
        queryset = Rental.objects.all()
        resource_name = 'rental'
        allowed_methods = ['get', 'post','put']
        fields = ['listingName','ownerName','room','price','summary']
        filtering = { "property" : ALL , "room":ALL,"price":ALL}
        authorization = DjangoAuthorization()

class GalleryImageResource(ModelResource):
    rental = fields.ForeignKey(RentalResource, 'rental', full=False, null=True, blank=True)

    class Meta:
        queryset = GalleryImage.objects.all()
        resource_name = 'gallery'
        allowed_methods = ['get','post','put']
        authorization = DjangoAuthorization()