Python Django:如何从不同的模型中获取最新的对象?

Python Django:如何从不同的模型中获取最新的对象?,python,django,Python,Django,我试图显示以下输出,其中圆柱体、问题和返回是不同的模型,我期望的视图是圆柱体表,其中仅显示最近创建的问题和返回条目, 例如: cylinderId=100,在issue表和return表中有两个条目,但在cylinder表中仅显示最近创建的条目,即:- cyId | createdAt | issuedDate | username | ReturnDate 100 | 5may,13:00| 6may,14:00 | anyone | 7may,15:00 以下是

我试图显示以下输出,其中圆柱体、问题和返回是不同的模型,我期望的视图是圆柱体表,其中仅显示最近创建的问题和返回条目, 例如:

cylinderId=100,在issue表和return表中有两个条目,但在cylinder表中仅显示最近创建的条目,即:-

cyId |   createdAt |  issuedDate  | username  | ReturnDate

100  |   5may,13:00|  6may,14:00  | anyone    | 7may,15:00
以下是模型:-

class Cylinder(models.Model):
    stachoice=[
    ('Fill','fill'),
    ('Empty','empty') 
    ]
    substachoice=[
    ('Available','available'), 
    ('Unavailable','unavailable'),
    ('Issued','issued') 
    
    ]
    cylinderId=models.CharField(max_length=50,primary_key=True,null=False)
    gasName=models.CharField(max_length=200)
    cylinderSize=models.CharField(max_length=30)
    Status=models.CharField(max_length=40,choices=stachoice,default='fill')
    Availability=models.CharField(max_length=40,choices=substachoice,default="Available")
    EntryDate=models.DateTimeField(default=timezone.now)
    
    

    def get_absolute_url(self):
        return reverse('cylinderDetail',args=[(self.cylinderId)])

    def __str__(self):
        return str(self.cylinderId)

class Issue(models.Model):
    cylinder=models.ForeignKey('Cylinder',on_delete=models.CASCADE)
    userName=models.CharField(max_length=60,null=False)
    issueDate=models.DateTimeField(default=timezone.now)
    
    def save(self,*args,**kwargs):
        if not self.pk: 
            if self.cylinder.Availability=='Available':
                Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability=('Issued'))

        super().save(*args,**kwargs)
        
    def __str__(self):
        
        return str(self.userName) 


class Return(models.Model):
    fill=[
    ('Fill','fill'),
    ('Empty','empty'),
    ('refill','Refill')
    ]

    ava=[
    ('yes','YES'),
    ('no','NO')
    ]
    cylinder=models.ForeignKey('Cylinder',on_delete=models.CASCADE)
    availability=models.CharField(max_length=20,choices=ava)
    status=models.CharField(max_length=10,choices=fill)
    returnDate=models.DateTimeField(default=timezone.now)
    def save(self,*args,**kwargs):
        if not self.pk:

            if self.cylinder.Availability=='Issued':
                
                if self.availability=='YES' or self.availability=='yes':
                    Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability='Available')
                    if self.status=='empty' or self.status=='Empty':
                        Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Status='Empty')
                else:
                    Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability='Unavailable')
                    if self.status=='refill' or self.status=='Refill':
                        Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Status='Refill')
                    if self.status=='empty' or self.status=='Empty':
                        Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Status='Empty')


        super().save(*args,**kwargs)

    def __str__(self):
        return str(self.cylinder)
视图:-

def cylinderListView(request):
    
    cylinder=Cylinder.objects.pefetch_related().order_by('-EntryDate')
    
    return render(request,'entry/cylinderList.html',locals())
模板cylinderList.html:-

{%for cy in cylinder %}
                    <tr bgcolor="#e6f0ff" align="center">
                        
                    <td align="center" height="10" 
                width="50"><a style="border-width: 0px" href="{{cy.get_absolute_url}}">{{cy.cylinderId}}<a></td>
               
                    <td align="center" height="10" 
                width="50">{{cy.EntryDate}}</td>
                    <td align="center" height="10" 
                width="50">{{cy.gasName}}</td>
                <td align="center" height="10" 
                width="50">
                    {{cy.cylinderSize}}</td>
                    <td align="center" height="10" 
                width="50">
                    {{cy.Status}}</td>
                    <td align="center" height="10" 
                width="50">{{cy.Availability}}</td>

               
                {% if cy.issue_set.all%}
                
                {% for issue in cy.issue_set.all %}

               
                <td align="center" height="10" 
                width="50">{{issue.issueDate}}</td>
                <td align="center" height="10" 
                width="50">{{issue.userName}}</td>
                
               {% endfor %}
                
                {% else %}
                <td align="center" height="10" 
                width="50">-</td>
                <td align="center" height="10" 
                width="50">-</td>

                {% endif%}


                 {% if cy.return_set.all%}
                
                {% for return in cy.return_set.all %}
                
                <td align="center" height="10" 
                width="50">{{return.returnDate}}</td>
              
               {% endfor %}
                
                {% else %}
                
                <td align="center" height="10" 
                width="50">-</td>

                {% endif%}


                                    
                
                    </tr>

                    {% endfor %}
                </tbody>

            {% else %}
{%用于气缸%中的cy}

对于这个结果,我应该怎么做?请帮助:)

您可以使用该方法

这将根据
CreatedAt
字段返回表中最新的圆柱体对象

如果要列出最新的气缸,请使用

Cylinder.objects.all().order_by('-EntryDate')    

只需将它们查询为
圆柱体.objects.order_by('-pk')

请将您的模型添加到问题中。@AbdulAzizBarkatdone@ShagunRaghav只是想澄清一下,您想获取最新版本并返回每个气缸的行吗?@yovelcohen Yes您应该使用预回迁_来完成此操作。请阅读文档。感谢您的关注:),但它只返回单个气缸条目,我想在issue表和return表中显示所有气缸id及其各自的最新条目。@ShagunRaghav查看更新的post@ShagunRaghav这对您有效吗?没有导致预期的输出。有任何错误吗?通过执行此查询,我能够获取问题条目并返回还有参赛作品吗?如果是,则如何查询?您可以将单个
气缸的
条目查询为
气缸对象问题设置为所有()
。如果您想要获得气缸列表的所有问题条目,则可以通过
for
循环。
Return也一样。通过查询issue and Return,它将返回为该圆柱体id(cylinderId=pk)创建的所有条目,但我只需要一个最近为该特定圆柱体id创建的条目。请观察我添加的表格图片。只需使用
cylinder\u obj.issue\u set.order\u By('-pk'))
对于最后3个对象,您可以按('-pk')执行
列表(圆柱体对象发布设置顺序)[:-3]
不会产生预期输出。
Cylinder.objects.all().order_by('-EntryDate')