D
D
Dmitry2016-03-31 07:34:14
Django
Dmitry, 2016-03-31 07:34:14

How to compare 2 ForeignKeys?

There are such models:

class Client(models.Model):
    full_name = models.CharField('Full name', max_length=45)

class Document(models.Model):
    description = models.CharField('Description', max_length=45)
    client = models.ForeignKey('Client')

class Ticket(models.Model):
    description = models.CharField('Description', max_length=255)
    client = models.ForeignKey('Client')
    document = models.ForeignKey('Document')

So here's the question:
Let's say I'm creating a new Ticket, but accidentally added one client and another client's documents, how can I avoid this?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Savchuk, 2016-03-31
@pyHammer

I support iegor . Of course, I'm not familiar with your task. But I assume that the document refers to a specific client, and the ticket, in turn, refers to a specific document.
It should be something like this:

class Client(models.Model):
    full_name = models.CharField('Full name', max_length=45)

class Document(models.Model):
    description = models.CharField('Description', max_length=45)
    client = models.ForeignKey('Client')

class Ticket(models.Model):
    description = models.CharField('Description', max_length=255)
    document = models.ForeignKey('Document')

Having such a DB structure, your problem will disappear.

I
iegor, 2016-03-31
@iegor

Your base composition is incorrect, think about relationships, read about normal forms.

D
Dmitry, 2016-03-31
@pyHammer

I assumed that you can fill it like this.

doc = Document.objects.get(pk=request.data['document'])
Ticket.objects.create(description=u"Бла Бла", client=doc.client, document=doc)

Then there is no need to pass client_id in POST request. But is this correct from a REST perspective?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question