1

I'm beginner with Django and I have problem to register model array of object from another class

Example:

class Trigger(models.Model):
   id = models.IntegerField()
   name = models.TextField()
   description = models.TextField()


class Host(models.Model):
   id = models.IntegerField()
   triggers = [] # <--- Array of Trigger instances here

How can I rewrite empty bracets to django model?

2
  • can a trigger belong to multiple hosts? Commented Jun 21, 2018 at 11:07
  • One trigger (instance) can belong only to one host. Commented Jun 21, 2018 at 11:08

1 Answer 1

1

You usually do that by adding a ForeignKey [django-doc] to a trigger that references to the Host, and then use as related_name= here 'triggers':

class Host(models.Model):
   id = models.IntegerField()

class Trigger(models.Model):
    id = models.IntegerField()
    name = models.TextField()
    description = models.TextField()
    host = ForeignKey(Host, on_delete=models.CASCADE, related_name='triggers')

Django will that add a reverse relation to Host. So you can then query somehost.triggers, which is a RelatedManager, to for example obtain .all(), elements, or .filter(..) these. So somehost.triggers.all() will result in a QuerySet that contains all Trigger objects with as host the somehost instance.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.