【问题标题】:Is it possible to have a generic field in django models?django模型中是否可以有一个通用字段?
【发布时间】:2022-01-24 23:07:11
【问题描述】:

我目前正在尝试为聊天应用程序设计数据库架构。
我对存储每条消息的内容的字段类型有些困惑。
这是聊天消息的部分完成的数据库架构:

...
...
...


# types of chat messages available
TEXT = 'text'
IMAGE = 'image'
...


MESSAGE_TYPE = [
    (TEXT, _('Chat message type : Text')),
    (IMAGE, _('Chat message type : Image')),
    ....
]

# User class represents a user of the application

class ChatMessage(models.Model):
    """
    Class for storing chat messages between `Users`
    """

    # type of the message
    message_type = models.CharField(choices=MESSAGE_TYPE, max_length=50, null=False)

    # user who created the text message
    sender = models.ForeignKey(User,related_name='sender', on_delete=models.CASCADE, null=False)

    # user who is supposed to receive the message
    recipient = models.ForeignKey(User,related_name='recipient', on_delete=models.CASCADE, null=False)

    # timestamp at which the message was created
    created_at = models.DateTimeField(default=timezone.now)

    # whether the recipient has seen the message
    seen = models.BooleanField()

    # content of the chat message
    content = .....

我计划使用编码器/解码器实用程序来解释 content 使用 message_type 字段的不同类型的聊天消息。但我很难指定适合执行此操作的字段。


这个数据库设计是否足以执行这项任务?我应该求助于其他模式吗?我正在使用 PostgreSQL。

我们将不胜感激。


感谢阅读。

【问题讨论】:

  • 你可以有一个通用的外键和每个消息类型的模型?

标签: python django django-models database-design django-orm


【解决方案1】:

CharFieldImageField对于数据库没有区别,django使用FileField时将文件路径保存到databse并保存到upload_to路径。

【讨论】:

  • 感谢您的回复。是的,ImageFieldURLFieldCharField(或TextField?)只要以字符串格式存储内容就足够了。我只是想知道是否可以为 Django ORM 以更“可解释”的方式存储数据。但如果没有别的办法,那也无妨。
猜你喜欢
  • 1970-01-01
  • 2017-04-22
  • 2021-07-20
  • 2017-02-01
  • 2020-01-19
  • 1970-01-01
  • 2015-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多