我有两个模型:模型订单
class Order(models.Model):
truck = models.ForeignKey(Truck, on_delete=models.CASCADE, related_name='relation_truck',default=None)
date= models.DateField()
product=models.CharField(max_length=30)
depot = models.CharField(max_length=10)
volume = models.CharField(max_length=30, blank=True)
volume_delivered = models.CharField(max_length=30, blank=True)
order_status = models.CharField(max_length=50, blank=True)
pub_date = models.DateTimeField(auto_now_add=True, blank=True)
和另一个模型加载模型:
class Loaded(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='relation_order',default=None)
status = models.CharField(max_length=50, blank=True)
我想在视图中使用模型order_status=Released
上的模型Loaded
中的Order
和Loaded
来提交对象,因为我有外键顺序。
在我看来,我有类似的东西:
def loading(request):
loaded = Loaded.objects.filter(order__order_status__in=['Loaded', 'Released'])
return render(request, 'loadings.html' , {'loaded':loaded})
在我的HTML中:
<table id="datatable2" class="table order-column hover">
<thead>
<tr>
<th>Truck NO.</th>
<th>Date</th>
<th>Product</th>
<th>Volume</th>
<th>Volume @20</th>
<th>Depot</th>
<th>Driver</th>
<th>Driver Tel</th>
<th>Driver ID</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{% for car in loaded %}
<tr class="gradeX">
<td>{{car.order.truck.truck_number}}</td>
<td>{{car.order.date}}</td>
<td>{{car.order.product}}</td>
<td>{{car.order.volume}}</td>
<td>{{car.order.volume_delivered}}</td>
<td>{{car.order.depot}}</td>
<td>{{car.order.truck.driver_name}}</td>
<td>{{car.order.truck.driver_phone_number}}</td>
<td>{{car.order.truck.driver_id_number}}</td>
<td><input type="checkbox" id="toggle-two"></td>
</tr>
{% endfor %}
</tbody>
</table>
我想要的是order_status Loaded和Received仅在我的loadings.html中显示的订单
试试这个:
loaded_or_released = Loaded.objects.filter(Q(order__order_status='Loaded') | Q(order__order_status='Released') )[0:200]
首先让我解释一下这个问题,这样我才能确保我正确理解了这个问题!
这意味着1
订单可以加载n
项目。
您希望所有已加载的项目在Loaded
或Released
中具有order_status。
Django one-to-many relationship lookup
如果这是你想要实现的目标,那么
all_loaded_items = Loaded.objects.filter(order__order_status__in=['Loaded', 'Released'])
在__
拆分参数名后的过滤器参数中
order
是外国领域order_status
是外国领域的领域in
是运算符中类似mysql的运算符其中all_loaded_items的类型为QuerySet。