Reputation: 3289
I want to create a queryset of the Plaque model and Veteran (ForeignKey) model into a combined queryset called queryset_list.
Model
class Plaque(models.Model):
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='plaques', default=1)
group = models.ForeignKey(Group, blank=True, null=True, verbose_name='Group Name')
veteran = models.ForeignKey(Veteran, blank=True, null=True)
...
View
def plaque_list(request):
today = timezone.now().date()
plaques = Plaque.objects.all()
veterans = Plaque.objects.all()
queryset_list = plaques | veterans
# queryset_list = Plaque.objects.active().order_by('first_name')
...
Upvotes: 0
Views: 729
Reputation: 99
You should be able to use the select_related method.
queryset_list = Plaque.objects.select_related('Veteran').all().order_by('first_name')
The detail is provided in the Django documentation.
Upvotes: 0
Reputation: 22841
It's not clear to me what you're trying to do from your question and your view code confuses things further as you assign the result of Plaque.objects.all()
to two different variables and then put them together. The ForeignKey
objects on the Plaque
model will all be available in the queryset. You can use select_related
to make sure you pull them all back efficiently, like so:
plaques = Plaque.objects.select_related("veteran").all()
for p in plaques:
print p.veteran
N.B., the .all()
isn't strictly necessary but I wanted to make it clear I was using the same query as you and simply adding to it.
Upvotes: 1