Skip to main content
 首页 » 编程设计

python之使用reactjs从api获取外键对象

2025年05月04日11telwanggs

我很困惑,继续我的项目变得非常困难。我正在开发租赁系统应用程序,用户可以在其中注册他们的空间(包括所有者姓名、列表名称、电子邮件、摘要、他们房间的多张图片等)。我为此创建了两个表。一个用于租赁详细信息,另一个画廊用于一次租赁的多个图像。 我为两者创建了一个 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) 

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

用于获取数据的reactjs代码

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

由于租金和画廊的网址不同,我现在如何获取与该租金相关的图像? 您的帮助将不胜感激。 谢谢

请您参考如下方法:

参见: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()