class Publisher(models.Model):
name = models.CharField(max_length=300, null=True, blank=True)
class Book(models.Model):
name = models.CharField(max_length=300, null=True, blank=True)
publisher = models.ManyToManyField(Publisher,related_name='b', null=True)
_published_at = models.DateTimeField()
from polls.models import Book, Publisher
p1=Publisher.objects.get(id=1)
p1.b.clear()
p1.save()
b6=Book.objects.get(id=6)
p1.b.add(b6)
b6._published_at = datetime.now()
p1.save()
b5=Book.objects.get(id=5)
p1.b.add(b5)
b5._published_at = datetime.now()
p1.save()
b7=Book.objects.get(id=7)
p1.b.add(b7)
b7._published_at = datetime.now()
p1.save()
p2 = Publisher.objects.get(id=2)
p2.b.clear()
p2.save()
b7=Book.objects.get(id=7)
p2.b.add(b7)
b7._published_at = datetime.now()
p2.save()
b6=Book.objects.get(id=6)
p2.b.add(b6)
b6._published_at = datetime.now()
p2.save()
b5=Book.objects.get(id=5)
p2.b.add(b5)
b5._published_at = datetime.now()
p2.save()
print p1.b.order_by("_published_at")
print p2.b.order_by("_published_at")
打印
[Book: b7, Book: b6, Book: b5]
[Book: b7, Book: b6, Book: b5]
虽然我希望它以与我这样添加它们相同的顺序打印
[Book: b6, Book: b5, Book: b7]
[Book: b7, Book: b6, Book: b5]
请您参考如下方法:
当您添加它们时,您会忘记添加它们的顺序,因为它只设置 Book 的外键。
您可以做的是将 DateTimeField() 添加到您的 Book 并在将其添加到出版商并按其排序时设置它。
类似于:
class Book(models.Model):
name = models.CharField(max_length=300, null=True, blank=True)
_published_at = models.DateTimeField()
publisher = models.ForeignKey(Publisher,related_name='b', null=True)
添加的时候
p=Publisher.objects.get(id=2)
p.b.clear()
p.save()
b6=Book.objects.get(id=6)
p.b.add(b6)
b6._published = datetime.now()
b6.save()
p.save()
b5=Book.objects.get(id=5)
p.b.add(b5)
b5._published = datetime.now()
b5.save()
p.save()
b7=Book.objects.get(id=7)
p.b.add(b7)
b7._published = datetime.now()
b7.save()
p.save()
打印时:
p.b.order_by("_published_at")
编辑: 对于您关于 ManyToManyField 的问题,您需要一个自定义的“through”模型 见https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships
class Publisher(models.Model):
name = models.CharField(max_length=300, null=True, blank=True)
class Book(models.Model):
name = models.CharField(max_length=300, null=True, blank=True)
publisher = models.ManyToManyField(Publisher,related_name='b',through="Publication",null=True)
_published_at = models.DateTimeField()
class Publication(models.Model):
book = models.ForeignKey(Book, on_delete=models.CASCADE)
publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)
_published_at = models.DateField()
class Meta:
ordering = ['_published_at']
此外,您不能使用 add() 添加新的发布者,您需要定义新的模型才能这样做。
所以要将 Publisher p3 添加到 book b7,你需要做
Publication.objects.create(book=b7, publisher=p3, _published_at=datetime.now())
他们现在应该自动订购了
