多对多Django模型

kadbb459  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(96)

你好,我试图找出最好的方式来设计这个模型,这是我到目前为止,但我遇到的问题有一个开始和结束日期每服务每客户

class Customer(models.Model):
    name     = models.CharField(max_length=255, null=False, unique=True)
    services = models.ManyToManyField(Service)
    
class Service(models.Model):
    name = models.CharField(max_length=255, null=False)

字符串
为了让数据看起来像这样,设计它的最佳方法是什么:

Customer        ||      Services        ||      Start       ||      End
Customer A          Service A               1/1/2001        1/1/2010
                    Service B               2/2/2002        2/2/2011
                    Service C               3/3/2003        3/3/2012
                    
Customer B          Service A               4/4/2004        4/4/2014
                    Service C               5/5/2005        5/5/2015


这几天我一直在绞尽脑汁想设计这个模型的最佳方法,如果能得到任何帮助,我将不胜感激。

kgqe7b3p

kgqe7b3p1#

使用中间表。

class Customer(models.Model):
    name = models.CharField(max_length=255, null=False, unique=True)
    
class Service(models.Model):
    name = models.CharField(max_length=255, null=False)
    architecture = models.NameField()
    
class customer_services(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, related_name='customer_service_entries')
    service = models.ForeignKey(Service, on_delete=models.SET_NULL, null=True, related_name='customer_service_entries')
    start = models.DateField()
    end = models.DateField()

字符串
使用上面的related_name参数,你可以使用一个名为customer_service_entries的prop从目标记录中遍历外键。一个Django模板示例,其中customers作为Customer示例的列表传递:

{% for customer in customers %}
    <p> Customer is {{ customer }}</p>
    <ul> Services:
        {% for entry in customer.customer_service_entries.all %}
            <li>{{ entry.service }} (architecture:{{ entry.service.architecture|default_if_none:"None" }})</li>
        {% endfor %}
    </ul>
{% endfor %}

相关问题