szaman
szaman

Reputation: 6756

unique_together in Table with ForeignKey pointing to itself

I have a Table described:

name = models.CharField(max_length=70)
parent = models.ForeignKey('self', null=True, blank=True)

Lets assume that we have two parents:

Table(id=1, name="first") Table(id=2, name="second")

When I create children:

Table(name="first", parent=1) Table(name="first", parent=2)

save objects should pass, but when I enter again and save

Table(name="first_child", parent=1)

it should fail. How can I do it? Unique in name is not a solution because parent and child can have the same name.

Upvotes: 0

Views: 297

Answers (2)

szaman
szaman

Reputation: 6756

As I wrote in comment

unique_together = ('name', 'parent')

was good way, bu it was only part of solution. I also made clean function with such code:

    if self.parent is None:
        try:
            result = Table.objects.filter(name=self.name, parent=None)
            if result.count():
                raise
        except Exception as ex:
            raise ValidationError('Record with this name already exists')

This part checked if there is no such record without parent. So it works like unique but only for records without parent.

Upvotes: 0

lprsd
lprsd

Reputation: 87077

Use unique=True, or a OnetoOneKey, instead of the ForeignKey. Refer the documentation.

Upvotes: 2

Related Questions