简体   繁体   中英

Django unique together relationship with field and manytomany on self

I'm try create post with language and content, and relate it on other versions of same page, but I'm get stuck

class Page(models.Model):
    content = models.TextField()
    language = models.CharField(max_length=7, choices=settings.LANGUAGES)
    versions = models.ManyToManyField('self', blank=True)
    class Meta:
        unique_together = ('language', 'versions',)

This will not work properly, because Django not allow make "unique" ManyToMany fields.

Then I'm try make same relationship trough related model:

class VersionsPage(models.Model):
    pass
    # ToDo: add unique together here,  to foreign key field

class Page(models.Model):
    ...
    versions = models.ManyToManyField('self', blank=True, through="VersionsPage")

Anyone know how to make that without using symmetrical=False?

I think you are looking for something like this:

class Page(models.Model):
    pass

class PageVersion(models.Model):
    page = models.ForeignKey(Page, related_name='versions')
    content = models.TextField()
    language = models.CharField(max_length=7, choices=settings.LANGUAGES)

    class Meta:
        unique_together = ('page', 'language',)


#getting all page versions:
page = Page.objects.get(pk=some_id)
versions = page.versions.all()

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