Reputation: 605
I have two models from which I'd like to get one result on a foreign key.
# Master List:
class Block(models.Model):
lesson = models.ForeignKey('Lesson')
name = models.CharField(max_length=100)
# Contains revisions, i.e. updates:
class BlockContent(models.Model):
block = models.ForeignKey('Block')
content = models.TextField()
type = models.IntegerField(default=1)
revision = models.IntegerField(default=0)
latest = models.BooleanField(default=True)
Ideally for template purposes, I'd like to be able to call block.content
or block.type
for instance, but this doesn't seem to be easily possible.
Getting the BlockContent
by foreign key seems to be a pain- despite there only being a one-to-one result in this specific view, it requires .all() and a lots of iteration.
Stuff I've tried:
additional = BlockContent.objects.get(block=block.id)
block.blockcontent_set.add(additional)
Upvotes: 1
Views: 383
Reputation: 3698
What you have is a one to many relationship in which Block
can have many BlockContent
objects.
The way to get content from a block is by using reverse relation, I don't see a problem with that:
content = block.blockcontent_set.all()[0].content
to get the content
of the first blockcontent
in the queryset.
Of course order_by
and all other queryset Django goodnes can be used here.
You could also define a related_name to:
class BlockContent(models.Model):
block = models.ForeignKey('Block', related_name=blockcontent)
and use it like:
content = block.blockcontent.all()[0].content
Upvotes: 1