Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用reactjs从api获取外键对象_Python_Django_Api_Reactjs_Tastypie - Fatal编程技术网

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

Python 使用reactjs从api获取外键对象,python,django,api,reactjs,tastypie,Python,Django,Api,Reactjs,Tastypie,我很困惑,我很难继续我的项目。我正在开发租赁系统应用程序,用户可以在其中注册他们的空间(包括所有者姓名、列表名、电子邮件、摘要、他们房间的多个图像等)。我为此创建了两个表。一个用于查看租赁详细信息,另一个用于查看多张图片的图库用于查看一次租赁。 我为两者都创建了一个api资源。我还可以将数据保存到数据库中。我成功地使用reactjs和tastpyie获取了租赁详细信息,但我无法获取与该租赁相关的图像。对此我应该怎么做 型号.py class Rental(models.Model): o

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

型号.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)
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()
api.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)
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>
            )
    }
}
导出默认类RoomList扩展React.Component{
建造师(道具){
超级(道具);
this.state={rooms:[]}
}
componentDidMount(){
log('componentDidMount');
这是.loadRoomFromServer();
}
loadRoomFromServer(){
$.ajax({
url:“/api/v1/rental/”,
数据类型:'json',
成功:(数据)=>{
console.log('data',data);
this.setState({rooms:data.objects});
console.log('success');
},
错误:(xhr、状态、错误)=>{
错误(url、状态、err.toString());
}
});
}
render(){
console.log('rooms',this.state.rooms);
让listOfRoom=this.state.rooms.map((room,id)=>{
返回(
)
});
log('listOfRoom',listOfRoom);
返回(
{listOfRoom}
)
}
}
class.Component{
render(){
返回(
{this.props.name}
{this.props.price}

{this.props.number}

) } }
由于租赁和画廊的url不同,我现在如何获取与该租赁相关的图像? 谢谢你的帮助。 谢谢

请参见:

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()

在序列化程序中,包括与文件对象关联的URL(请参阅)。这样,您就可以将其插入img标记的src属性中。图像以不同的id上载。我如何将多个图像关联到其租金。如果您想从租金中获取图像,您可以执行类似于rental.galleryimage_set.all()的操作不,图像有一个属性url,因此galleryimage.image.urlSide注意:使用ImageField存储图像本身。仅为第一个租用的画廊分配了画廊资源列表(“画廊”:[“/api/v1/gallery/1/”,“/api/v1/gallery/2/”])。另一个有空的画廊。另外,在访问gallery api时,我得到{“error”:“模型'GalleryImage:writingDescribingData6_RfgeRIX.png'具有空属性'rental',并且不允许空值。”}除第一个rent对象外,gallery列表仍然为空。我已经发布了一个链接,以清晰显示上传的图像已保存到数据库,但画廊对象仍显示为空列表。我必须从管理端手动分配它,否则画廊对象为空。第一次租赁已正确填充了相关的画廊图像。您确定第二次租赁有相关数据吗?