nykon
nykon

Reputation: 625

django model, a field which required two different fields

I am building a small web-app. The principle is that a user can register and add a publication (some article which he found in the web) to the database. I wanted to add some infos about the publication like: the title, abstract, date of publication and the authors. The problem is that author/authors could be: the registered user (it is possible that the user is one of the author of the article) or unknown person with name, surname, institute and home-page or mix the registered user and unknown person/persons. How could I implement that in my model?

Right now I have wrote the user-profile for registered users. It is always good to store some additional infos about the users like e.g. the institute.

For authors of the articles I have inherit the class with the user-profile class:/ that is not good solution, because unknown author != registered user, but they have the same fields: name, surname, institute, home-page and so on.

I would be very grateful for any tip :)

Upvotes: 0

Views: 69

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239320

I would make the publication link to an Author instead of User, then you'd set up the Author class like:

class Author(models.Model):
    user = models.OneToOneField(User, blank=True, null=True)
    first_name = models.CharField(max_length=50, blank=True)
    last_name = models.CharField(max_length=50, blank=True)
    # etc

The idea is that you can generically related the publication to the concept of an author and then allow for the author to be either a registered user (in which case, you'd use the details from the user attribute, or an anonymous user (where you would use the other fields on Author)

You could then add some utility methods to Author to return the proper data. For example:

def get_first_name(self):
    if self.user is not None:
        return self.user.first_name
    else:
        return self.first_name

There's a lot more you can do to make it even more seamless, but this is the general idea.

Upvotes: 1

Related Questions