Home > Blockchain >  how to get a column value of foreign key in the form of object?
how to get a column value of foreign key in the form of object?

Time:12-14

There is 2 models Registration and RegistrationCompletedByUser, I want Registration queryset from RegistrationCompletedByUser with filters(user=request.user, registration__in=some_value, is_completed=True) over RegistrationCompletedByUser. Hence result should be like <QuerySet [<Registration: No name>, <Registration: p2>, <Registration: p-1>]>.

Now what I tried is Registration.objects.prefetch_related('registrationcompletedbyuser_set') but filters() not working. Another way I tried is model Managers but don't pass parameters for custom filtering.

models.py

class Registration(models.Model):
  name=models.CharField(max_length=255)
  number=models.SmallIntegerField(null=True, blank=True)

class RegistrationCompletedByUser(models.Model):
  user = models.ForeignKey(User, on_delete=models.CASCADE)
  registration= models.ForeignKey(Registration, on_delete=models.CASCADE)
  points = models.SmallIntegerField(default=100)
  is_completed = models.BooleanField(default=False)

CodePudding user response:

If I understood this properly, you want to get all Registrations that related to a query instead of a single object.

qs_1 = RegistrationCompletedByUser.objects.filter(user=request.user, is_completed=True).values_list("registration__id", flat=True)

qs_2 = Registration.objects.filter(id__in=qs_1)

CodePudding user response:

As I understood your question is related to django. So actually there is common way to get related query set from another. When you specify ForeignKey to another model actually django automatically creates 'Related Model' '_set' relation.

I actually didn't get from you question what you are intended to do. In your situation there are many RegistrationCompletedByUser related to one Registration. So what you can do it's to receive all RegistrationCompletedByUser instances from Registration instance by related name for ForeignKey registration of RegistrationCompletedByUser which in your case registration_set. Actually better to specify in RegistrationCompletedByUser model related name as attribute like this:

   models.ForeignKey(Registration, on_delete=models.CASCADE, 
         related_name='registrations')

And after this let's say you have instance of Registration reg1. So to receive queryset of RegistrationCompletedByUser:

   reg1.registrations.all()

And you can use filter on it with attributes from Registration model. And if you want to receive Registration from RegistrationCompletedByUser, again in your case it's just one Registration to many RegistrationCompletedByUser, so let's say we have reg_completed_1, to receive it's only one registration:

  reg = reg_completed_1.registration
  • Related