簡體   English   中英

Django ManyToMany字段

[英]Django ManyToMany Field

我需要制作一個智能菜單,為此我需要一個ManyToMany關系。

我的模型是:

from django.db import models

    class Health_plan(models.Model):
        a = models.IntegerField ()
        b = models.IntegerField ()

   class Doctors_list(models.Model):

        name = models.CharField(max_length=30)
        hp_id = models.ManyToManyField(Health_plan)

        def __unicode__(self):
            return self.name

如何在數據庫中建立這種關系? 我當時在考慮將health_plans (a,b)列為一欄,將醫生列為行,分別用0和1標識他們涵蓋的health_plans。

有人告訴我這是對ManyToManyField的濫用,我不知道該采取什么措施。

感謝幫助

health_plans列為列的方法不一定是錯誤的,但這意味着您擁有固定數量的健康計划,並且永遠不會添加新的健康計划。

關系數據庫中多對多關系的傳統方法是在中間引入一個表。 該表僅包含醫生與健康計划之間的關聯。

如果您的Doctor表包含:

id    name
1     foo
2     bar

還有一個HealthPlan表:

id    model
1     a
2     b

然后,您添加一個表格Doctor_HealthPlan ,如下所示:

doctor_id    healthplan_id
1            2
2            1
2            2

django中的ManyToMany字段類型將自動為您創建此表。 你的代碼是正確的,但你或許應該重新命名hp_id喜歡的東西health_plans ,因為它是一個代理,允許您訪問的相關醫生健康計划列表。

Django的ORM已經處理了中間表,因此您不必“在數據庫中建立此關系”,但是鑒於您的問題,您顯然需要學習適當的關系模型規范化-如果您不了解關系模型,Django的ORM和其他任何SQL FWIW都將無處可尋。

作為記錄,在關系模型中,多對多關系被建模為在兩個其他表上都具有外鍵的關系(SQL中的“表”),即:

health_plan(#health_plan_id, name, ...)
doctor(#doctor_id, firstname, lastname, ...)
doctors_health_plans(#health_plan_id, #doctor_id)

因此,您的Django模型應為:

class HealthPlan(models.Model):
    # no need to define an 'id' field,
    # the ORM provides one by default
    name = models.CharField(....)

class Doctor(models.Model):
    firstname = models.CharField(....)
    lastname = models.CharField(....)
    health_plans = models.ManyToManyField(HealthPlan, related_name="doctors")

然后,您將可以獲得醫生的所有健康計划:

  doc = Doctor.objects.get(pk=xxxx)
  doc.health_plans.all()

以及所有醫生的健康計划:

  plan = HealthPlan.objects.get(pk=xxxx)
  plan.doctors.all()

FineManual(tm)像往常一樣是您的朋友...

您只需要先保存兩個模型,然后將healthplan實例添加到Doctors列表中即可。 Django將為您處理其余的工作。

例如 :

doctor_list = Doctors_list(name="Bwire")
health_plan.save()
doctor_list.save()

#Then add the plan to the doctors list.
doctor_list.hp_id.add(health_plan)

Django為您創建表格。 在您的項目文件夾中運行:

python manage.py syncdb

Health_plan和Doctors_list都是表。 “ a”和“ b”是Health_plan中的列。 “名稱”和“ hp_id”是Doctors_list中的列。 Django將在每個表中為id創建一列。 Django還將創建一個表“ Doctor_list_Health_plan”來存儲關系信息。

Django模型是Python類,因此適用Python命名約定。 使用HealthPlan和Doctor(CapitalizeWord單數)。

您的字段名稱有點抽象。 我建議您使用更具描述性的名稱。 例如:

class HealthPlan(models.Model):
    name = models.CharField()
    extra_care = models.BooleanField()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM