2

使用 django 版本 1.11.2 最终版。

我有下面的模型,用于小发票。在此过程中我进行了几次迁移,最终将unique_together = ('facture', 'article')约束添加到“线”模型中。但是,在运行时./manage.py makemigrations,未检测到任何更改。也尝试了unique_together = (('facture', 'article'),)语法,但得到相同的结果。

from django.db import models
from django.db.models import F, Sum
from personnes.models import Person

# Create your models here.
class Facture(models.Model):
    date = models.DateField(auto_now=True)
    client = models.ForeignKey(Person, related_name="factures", on_delete= models.CASCADE)
    articles = models.ManyToManyField("Article", through="Line", related_name="factures")

    @property
    def total(self):
        return self.lines.aggregate(total=Sum(F('count')*F('article__price')))

    def __str__(self):
        return "%s %s %s" % (self.id, self.date, self.client.first_name)

class Article(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=10, decimal_places=2)

    def __str__(self):
        return "%s %s" % (self.name, self.price)

class Line(models.Model):
    facture = models.ForeignKey(Facture, related_name="lines", on_delete=models.CASCADE)
    article = models.ForeignKey(Article, related_name="lines", on_delete=models.CASCADE)
    count = models.IntegerField(default=1)

    @property
    def amount(self):
        return self.count * self.article.price

    def __str__(self):
        return "facture %s - %s x %s %s" % (self.facture.id, self.count, self.article.name, self.article.price)

    class META:
        unique_together = ('facture', 'article')
4

1 回答 1

2

您错误地将元类大写。它应该是

class Line(models.Model):
    ...

    class Meta:
        unique_together = ('facture', 'article')
于 2017-06-09T10:36:01.227 回答