Как получить доступ к свойствам ForeignKey из models.py в django
Я хочу получить доступ к свойству другой модели из модели через ForeignKey. Например, если invoice_details
является ForeignKey для InvoiceMaster
, то я хочу, чтобы invoice_details
хранил значение InvoiceMaster
из invoice_number
, а не первичный ключ. Как я могу этого добиться?
Я пробовал следующее:
class OrderDetails(models.Model):
purchase_order_number = models.IntegerField(blank=True, null=True)
purchase_request_number = models.IntegerField(blank=True, null=True)
delivery_no = models.IntegerField(blank=True, null=True)
delivery_equipment = models.CharField(max_length=500, blank=True, null=True)
delivery_quantity = models.IntegerField(blank=True, null=True)
warranty_start_date = models.DateField()
warranty_end_date = models.DateField()
invoice_details = models.ForeignKey(InvoiceMaster, on_delete=models.CASCADE, blank=True, null=True).invoice_number
vendor_id = models.ForeignKey(VendorDetails, on_delete=models.CASCADE, blank=True, null=True).vendor_id
equipment_id = models.ForeignKey(EquipmentMaster, on_delete=models.CASCADE, blank=True, null=True).equipment_id
is_visible = models.IntegerField(default=1)
created_by = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
creation_date = models.DateTimeField(default=timezone.now)
Проверьте invoice_details
- Я попробовал добавить .invoice_number
в конец ForeignKey. Добавление .invoice_details
к InvoiceMaster
внутри скобок ForeignKey дало мне следующую ошибку: TypeError: ForeignKey(<django.db.models.query_utils.DeferredAttribute object at 0x10d632fd0>) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self'
Вот модуль InvoiceMaster
:
class InvoiceMaster(models.Model):
invoice_number = models.CharField(max_length=50, blank=True, null=True)
equipment_name = models.ForeignKey(EquipmentMaster, on_delete=models.CASCADE, blank=True, null=True).name
quantity = models.IntegerField(blank=True, null=True)
is_visible = models.IntegerField(default=1)
created_by = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
creation_date = models.DateTimeField(default=timezone.now)
По какой-то причине, хотя я сделал то же самое в equipment_name
здесь, что и в invoice_details
, Django не показывает ошибки. Для дополнительного контекста, пожалуйста, посмотрите на EquipmentMaster
, на который equipment_name
есть ссылка через ForeignKey.
class EquipmentMaster(models.Model):
equipment_id = models.CharField(max_length=50, blank=True, null=True)
equipment_type = models.CharField(max_length=50, choices=equipment_categories)
name = models.CharField(max_length=200, blank=True, null=True)
ram = models.CharField(max_length=100, blank=True, null=True)
storage = models.CharField(max_length=100, blank=True, null=True)
display_size = models.CharField(max_length=100, blank=True, null=True)
paper_size = models.CharField(max_length=100, blank=True, null=True)
operating_system = models.CharField(max_length=100, blank=True, null=True)
is_visible = models.IntegerField(default=1)
created_by = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
creation_date = models.DateTimeField(default=timezone.now)
Могу ли я спросить, с какой целью это делается?
А ForeignKey
- это только отношение к другому полю. Если это происходит только из-за отображения invoice_number
вместо пк, попробуйте добавить следующее:
class InvoiceMaster(models.Model):
invoice_number = models.CharField(max_length=50, blank=True, null=True)
# your other fields
def __str__(self).
return self.invoice_number
В противном случае вы можете получить номер_фактуры непосредственно из ForeignKey, как
order = OrderDetails.objects.get(pk=1)
invoice_number = order.invoice_details.invoice_number
Вы можете получить подробную информацию о InvoiceMaster
в OrderDetails
, выполнив следующие действия в OrderDetails
:
@property
def invoice_number(self):
return self.invoice_details.invoice_number
при этом вы можете получить invoice_number
из order_details, вызвав order_details.invoice_number
.
Возможно, вы захотите проверить, существует ли связь, прежде чем обращаться к полю foreignkey.