简体   繁体   English

如何在Django中不同模型的任何两个字段之间建立OneToOne关系?

[英]How do i have OneToOne relationship between any two fields of different models in Django?

class HmsMedicine(models.Model):
    id = models.IntegerField(primary_key=True)
    medicine_name = models.CharField(max_length=100)
    price = models.IntegerField(max_length=6)

class HmsBilling(models.Model):
    id = models.IntegerField(primary_key=True)
    regid = models.ForeignKey(HmsPatient, db_column='regid')
    medicine = models.ForeignKey(HmsMedicine, db_column='medicine')
    quantity = models.IntegerField()
    rate = models.IntegerField()

I want to have the values of price field in the rate field. 我想在rate字段中输入price字段的值。

class HmsBilling(models.Model):
    id = models.IntegerField(primary_key=True)
    regid = models.ForeignKey(HmsPatient, db_column='regid')
    medicine = models.ForeignKey(HmsMedicine, db_column='medicine')
    quantity = models.IntegerField()
    rate = models.ForeignKey(HmsMedicine, db_column='price')

hms = HmsBilling.objects.select_related().get(id=5)
hms.rate

this will give you the price for the billing with id = 5 (see this link for reference on select related) 这将为您提供ID = 5的结算价格(有关选择相关内容,请参阅此链接以获取参考)

better: 更好:

class HmsBilling(models.Model):
    id = models.IntegerField(primary_key=True)
    medicine = models.ForeignKey(HmsMedicine)
    quantity = models.IntegerField()

hms = HmsBilling.objects.select_related().get(id=5)
hms.medicine.price

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我在Django应用程序中的同一个类的两个对象之间有一个OneToOne关系。 是否有可能强制实现这种关系的独特性? - I have a OneToOne relationship between two objects of the same class in a Django app. Is it possible to enforce the uniqueness of this relationship? 如何以多对多关系在Django模型的两个字段之间执行计算 - How to performing calculation between two fields in Django models in a many to many relationship 在创建两个模型后,在两个模型之间创建关系。 (Python,Django,SQLite) - Creating a relationship between two models after both models have been created. (Python, Django, SQLite) 在Django中使用Foreignkey和OnetoOne关系构建模型? - building models with foreignkey and OnetoOne relationship in Django? Django中两个模型之间的ManyToMany关系 - ManyToMany Relationship between two models in Django 两个模型Django / python之间的关系 - Relationship between two models Django/python 如何“干净”地创建模型之间的Django / DRF序列化关系? - How do I 'cleanly' create this Django/DRF serialization relationship between models? 在两个不同模型中链接两个Django字段 - Linking two django fields in two different models Django:两种不同型号不同字段的操作 - Django: Operations on different fields of two different models Django中2个型号的关系 - Relationship between 2 models in Django
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM