简体   繁体   中英

Assigning Tag to object in Django ORM many-to-many relationship

I have three tables. Tag , QueryStringTag , and QueryString . QueryStringTag a third table that is created to connect Tag and QueryString and allow one Tag to be associated with many QueryString 's and vice versa. It contains two foreign keys. One pointed at Tag and one pointed at QueryString .

The flow goes like this. A QueryString object is created and saved in the database. After this, 4 Tags are created. I want to associate those takes with the particular QueryString object.

I have failed at all attempts so far. The docs are not providing much help and I have tried just about everything I can think of.

Here are my models...

class QueryString(BaseObject): 

    server_id = models.IntegerField()
    schema = models.CharField(max_length=255, blank=True)
    query = models.CharField(max_length=60000) 
    variables = models.TextField(blank=True)
    created_by = models.ForeignKey(User, related_name='queries_created')
    updated_by = models.ForeignKey(User, related_name='queries_last_edited')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField()
    touched_by = models.CharField(max_length=1000)
    config = models.TextField(blank=True)
    runs_started = models.IntegerField(default=0)
    runs_completed = models.IntegerField(default=0)
    runs_completed_duration = models.IntegerField(default=0) # total number of seconds spent running this query to completion
    formats = "pretty_html html json prettyjson csv excel tableau".split()

class Tag(models.Model):
    name = models.CharField(max_length=100)

class QueryStringTab(models.Model):
    tag = models.ForeignKey(Tag, related_name='querystringtag')
    querystring = models.ForeignKey(QueryString, related_name='querystringtag')

Here is my view...
(Keep in mind that query is a unique QueryString object that I am trying to associate with the four tags below)

tags = ['one', 'two', 'three', 'four']

for tag in tags:
    newtag = Tag(name=tag)
    newtag.save()
    query.querystringtab.tag(newtag.pk)

Can anyone point me in the right direction?

I'd suggest searching about here on StackOverflow. I found two probably relevant answers searching "python django many to many":

For example: Way to allow for duplicate many-to-many entries in Python/Django

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM