how to have database relationship with the active data. in django

Viewed 53

i have some active and non active data's in EVENT models and active data has the VISITORS form to fill ..so far i have tried OnetoOne relationship but it didn't succeed ..i am getting both active and non active field in VISITORs model..thank you for your time.

here is models.py

class Event(models.Model):
      event_id = models.AutoField
        Event_Name = models.CharField(max_length=50)
        description = RichTextField()
        date_And_time = models.DateTimeField()
        location=models.CharField(max_length=50)
        slugs = models.SlugField(max_length= 200,default="")
        picture = models.ImageField(upload_to='wildlife/picture', default="")
        active = models.BooleanField(default=False)

        class Meta:
            ordering = ["date_And_time"]
        def __str__(self):
            return self.Event_Name


class Eventvisitor(models.Model):

    event = models.OneToOneField(Event, on_delete=models.CASCADE,   related_name="eventvistor",default="")
    name = models.CharField(max_length=50)
    email = models.CharField(max_length=70, default="")
    phone = models.CharField(max_length=20,default="")
    date = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-date']
    def __str__(self):
        return self.email
1 Answers

You can limit the choices with limit_choices_to=… [Django-doc]. But likely what you want is a ForeignKey, since otherwise, each Event can have at most one related EventVisitor (a OneToOneField is basically a ForeignKey with a unique=True constraint).

class Eventvisitor(models.Model):
    event = models.ForeignKey(
        Event,
        limit_choices_to={'active': True},
        on_delete=models.CASCADE,
        related_name='eventvistors'
    )
    name = models.CharField(max_length=50)
    email = models.CharField(max_length=70, default="")
    phone = models.CharField(max_length=20,default="")
    date = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-date']

    def __str__(self):
        return self.email

Note that while one can only select Events with active=True, if you later set the .active field to False, items will still link to it, since the relation is not enforced at database level.

Related