我有两个模型,分别是卡车和订单,并且它们之间有关系。
from django.db import models
from django.contrib.auth.models import User
class Truck (models.Model):
truck_number = models.CharField(max_length=200);
condition = models.CharField(max_length=20);
insurance = models.CharField(max_length=20);
gps_tracking = models.CharField(max_length=20);
owner_name = models.CharField(max_length=20);
id_number = models.IntegerField();
telephone_number=models.IntegerField();
driver_name=models.CharField(max_length=30, default=None);
driver_id_number=models.IntegerField();
driver_phone_number=models.IntegerField();
driving_license=models.CharField(max_length=20);
good_conduct=models.CharField(max_length=30);
def __str__(self):
truck_number = self.truck_number
return truck_number
class Order(models.Model):
truck_number= models.Foreignkey(Truck,related_name='relation_truck')
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)
driver_name=models.ForeignKey(Truck, max_length=30,default=None)
driver_id_number=models.ForeignKey(Truck, related_name='relation_id')
driver_phone_number=models.ForeignKey(Truck, related_name='relation_tel')
order_status = models.CharField(max_length=50, blank=True)
def __str__(self):
truck_number = self.truck_number
return truck_number
所有带有外键的字段都将获取整个对象Truck,而不是外键的特定值。就像我想要truck_number以便仅从表Truck而不是整个Truck对象中获取truck_number一样。 我如何获取外键值而不是整个对象。
答案 0 :(得分:0)
根据您的评论,您需要以下内容:
Truck.objects.values_list('id', 'truck_number', 'driver_name', 'driver_id_number', 'driver_phone_number')
答案 1 :(得分:0)
我设法做到了,正如webbyfox所说的:
class OrderAdmin(admin.ModelAdmin):
fields = ('truck_number','date','product','depot','driver_name','driver_id_number','driver_phone_number')
form = OrderForm
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "truck_number":
kwargs["queryset"] = Truck.objects.values_list( 'truck_number', flat=True)
elif db_field.name == "driver_name":
kwargs["queryset"] = Truck.objects.values_list( 'driver_name', flat=True)
elif db_field.name == "driver_id_number":
kwargs["queryset"] = Truck.objects.values_list( 'driver_id_number', flat=True)
elif db_field.name == "driver_phone_number":
kwargs["queryset"] = Truck.objects.values_list( 'driver_phone_number', flat=True)
return super().formfield_for_foreignkey(db_field, request, **kwargs)
admin.site.register(Order, OrderAdmin)