简体   繁体   中英

Django Foreign Key Field assign one field with only one another field

I'm trying to create model TravelAgentDocumentType which consists of two ForeignKey's ie travel_agent and document_type the plan is to have one travel agent can have only one document type, below are my code snippet from models.

   class TravelAgentDocument(BaseModel):
        travel_agent = models.ForeignKey(TravelAgent, null=True, on_delete=models.CASCADE)
        document_type = models.ForeignKey(
            DocumentType,
            on_delete=models.SET_NULL,
            null=True
        )

and TravelAgent model is

class TravelAgent(BaseModel):
    name = models.CharField(
        max_length=100,
        unique=True,
        validators=[validate_travel_agent_name]
    )
    office_location = models.CharField(
        max_length=100,
        validators=[validate_location],
    )
    office_land_line_number = LandLineNumberField(blank=True)
    slug = models.SlugField(
        unique=True,
        blank=True)
    office_phone_number = PhoneNumberField(unique=True)

DocumentType model is

class DocumentType(BaseModel):
    name = models.CharField(
        max_length=20,
        unique=True,
        validators=[validate_document_name]
    )

how can I assign one travel agent with only one document type?

I think you want UniqueConstraint feature here.

class TravelAgentDocument(BaseModel):
        travel_agent = models.ForeignKey(TravelAgent, null=True, on_delete=models.CASCADE)
        document_type = models.ForeignKey(
            DocumentType,
            on_delete=models.SET_NULL,
            null=True
        )

      class Meta:
          constraints = [
                models.UniqueConstraint(fields=['travel_agent', 'document_type'], name='name of constraint')
                    ]

Try this :-

Class Travel_agent(models.Model):
    name = models.CharField(
        max_length=100,
        unique=True,
        validators=[validate_travel_agent_name]

        office_location = models.CharField(
        max_length=100,
        validators=[validate_location],
    )
    office_land_line_number = LandLineNumberField(blank=True)
    slug = models.SlugField(
        unique=True,
       blank=True)
    office_phone_number = PhoneNumberField(unique=True)

Class Agent_document(models.Model):
    docum = models.OneToOneField(Travel_agent, 
    on_delete=models.CASCADE,default='')

这是因为在您的 travelagentdocument 模型中,您已经使用外键创建了 document_type 字段。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM