bhargava.prabu
bhargava.prabu

Reputation: 708

Get not all values but specific values of field in another model with one to one field

I have two models. 1. courses 2. First Year

Here is course Model

class Courses(models.Model):
    class Meta:
        verbose_name_plural = 'Courses'

    year_choices = [
        ('----', '----'),
        ('First Year', 'First Year'),
        ('Second Year', 'Second Year'),
        ('Third Year', 'Third Year'),
        ('Fourth Year', 'Fourth Year'),
        ('Minor', 'Minor'),
    ]
    year = models.CharField(max_length=50,default='----',choices=year_choices)
    course_code = models.CharField(max_length=10,
                               default='',
                               validators=[MinLengthValidator(1)])

Here is FirstYear Model

class FirstYear(models.Model):
    class Meta:
        verbose_name_plural = '1. First Year'

    course   = models.OneToOneField(Courses,
                                    default='',
                                    on_delete=models.CASCADE)
    title = models.CharField(max_length=100,default='')


    def __str__(self):
        return '{}'.format(self.title).capitalize()

I'm new to Django. My question is I have to invoke the course_code field only if it is first year and not all year.

Example : Course Model
object-1 -> year = First Year
            course_code = HJK456
object-2 -> year = Second Year
            course_code = ERT890

Here I Have to get HJK456 in onetoone field only, not ERT890. I should display only the option choosed as first year. Help me how to filter.

Please help me here. Thank you.

Upvotes: 1

Views: 43

Answers (1)

azundo
azundo

Reputation: 6052

Use the limit_choices_to argument to restrict the options displayed in the admin: https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to

class FirstYear(models.Model):
    class Meta:
        verbose_name_plural = '1. First Year'

    course = models.OneToOneField(Courses,
                                  default='',
                                  on_delete=models.CASCADE,
                                  limit_choices_to={'year': 'First Year'})
    title = models.CharField(max_length=100,default='')

Upvotes: 1

Related Questions