django检索相关对象

时间:2016-12-31 07:11:32

标签: python django

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]

1 个答案:

答案 0 :(得分:2)

当你添加它们时,你会忘记添加它们的顺序,因为它只设置了Book的外键。

您可以做的是在您的图书中添加DateTimeField(),并在将其添加到发布商并按订单排序时进行设置。

类似的东西:

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您需要自定义“直通”模型的问题 见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())

现在应该自动订购