CrawlData モデルが common アプリケーション

CrawlData モデルが common アプリケーションで定義されており、別のアプリケーションのモデルを参照する必要がある場合、外部キーを使って参照できます。

例えば、別のアプリケーションが other_app で、そこに OtherModel というモデルがあるとします。CrawlData モデルが OtherModel を参照する場合、以下のようになります。

python
from django.db import models from utils_models import CustomDateTimeField #日本時間の作成日・更新日を返すクラス from common.models import CrawlSite from other_app.models import OtherModel class CrawlData(models.Model): """ クロール結果のHTML情報 """ url = models.URLField(primary_key=True) crawl_site = models.ForeignKey(CrawlSite, on_delete=models.CASCADE) other_model = models.ForeignKey(OtherModel, on_delete=models.CASCADE) # 別のアプリケーションのモデルを参照 html_content = models.TextField() html_sub_content = models.TextField(null=True) crawl_timestamp = models.DateTimeField() # 更新日時(自動追加) updated_at = CustomDateTimeField(auto_now=True) # 作成日時(自動追加) created_at = CustomDateTimeField(auto_now_add=True) def __str__(self): return f"CrawlData {self.url}"

このようにして、CrawlData モデルは other_app アプリケーションの OtherModel を参照する外部キーを持つことができます。

未分類

Posted by ぼっち