我是编程领域的新手&django。我有一些带有Foreing Key的模型,我必须连接两个表:ComponentInstance和;组件装运。我的新表应该具有ComponentInstance表,该表具有字段("component"、"serial_number"、"condition_received"、"date_receiveed"、"received_from"、"quantity"(和ComponentShipment表中具有新字段("date_shipped"、"shipped_to"、"shipped_condition"、"invoice"(的信息。我的表ComponentShipment通过字段"component"连接到表ComponentInstance,但并非所有"components"都已发货。因此,在我的新表中,如果组件未发货,则表ComponentShipment中的新字段('date_shipped'、'shipped_to'、'sshipped_condition'、'invoice'(将为Null。
class ComponentInstance(models.Model):
component = models.ForeignKey('Component', on_delete=models.CASCADE)
serial_number = models.CharField(max_length=50)
customer = models.ForeignKey('Customer', on_delete=models.CASCADE, default=1)
condition_received = models.ForeignKey("Condition", on_delete=models.CASCADE)
date_received = models.DateField(default=django.utils.timezone.now)
time_create = models.DateTimeField(auto_now_add=True)
time_update = models.DateTimeField(auto_now=True)
updated_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='updated_by_user', null=True, blank=True)
created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='created_by_user', null=True, blank=True)
received_from = models.CharField(max_length=30)
staff_received = models.ForeignKey("StoreStaff", on_delete=models.CASCADE)
quantity = models.PositiveSmallIntegerField(default=1)
unit = models.ForeignKey('QuantityType', on_delete=models.CASCADE, default=1)
location = models.ForeignKey('Location', on_delete=models.CASCADE, null=True, blank=True)
notes = models.CharField(max_length=50, null=True, blank=True)
def __str__(self):
return f"{self.component} {'S/N '} {self.serial_number}"
class Meta:
verbose_name = "Component"
verbose_name_plural = "Components"
ordering = ('component',)
class ComponentShipment(models.Model):
component = models.ForeignKey('ComponentInstance', on_delete=models.CASCADE)
date_shipped = models.DateField(default=django.utils.timezone.now)
shipped_to = models.CharField(max_length=30, null=True, blank=True)
shipped_condition = models.ForeignKey("Condition", on_delete=models.CASCADE)
invoice = models.CharField(max_length=30, null=True, blank=True)
staff_shipped = models.ForeignKey("StoreStaff", on_delete=models.CASCADE, null=True, blank=True)
scrapped_company = models.ForeignKey('RepairCompany', on_delete=models.CASCADE, null=True, blank=True)
def __str__(self):
return f'{self.component} {self.date_shipped} {self.shipped_to}'
我试图以不同的方式将这两张桌子连接起来,但没有任何效果;(如何才能做到这一点?感谢的帮助
您不需要加入,只需从ComponentShipment&然后您可以访问来自同一对象的数据。比如
componentShipment = ComponentShipment.objects.get(component = 'Id value of component')
现在,您可以访问ComponentInstance模型中的值
print(componentShipment.serial_number)
print(componentShipment.customer)
希望这会有所帮助。