How to use the django.db.models.ForeignKey function in Django

To help you get started, we’ve selected a few Django examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github dstl / lighthouse / apps / teams / models.py View on Github external
# (c) Crown Owned Copyright, 2016. Dstl.

from django.core.urlresolvers import reverse
from django.db import models

from apps.organisations.models import Organisation


class Team(models.Model):
    name = models.CharField(max_length=256, unique=True)
    organisation = models.ForeignKey(Organisation)

    class Meta:
        ordering = ["name"]

    @classmethod
    def with_most_members(cls):
        return Team.objects.all().annotate(
            count=models.Count('user')
        ).filter(count__gte=1).order_by('-count', 'name')

    def get_absolute_url(self):
        return reverse('team-detail', kwargs={'pk': self.pk})

    def __str__(self):
        return self.name
github bcgov / gwells / gwells / models.py View on Github external
comments = models.CharField(max_length=3000, blank=True, null=True)
    alternative_specs_submitted = models.BooleanField(default=False, verbose_name='Alternative specs submitted (if required)', choices=((False, 'No'), (True, 'Yes')))

    well_yield_unit = models.ForeignKey(WellYieldUnit, db_column='well_yield_unit_guid', on_delete=models.CASCADE, blank=True, null=True)
    diameter = models.CharField(max_length=9, blank=True)  #want to be integer in future

    observation_well_number = models.CharField(max_length=3, blank=True, null=True, verbose_name="Observation Well Number")
    observation_well_status = models.CharField(max_length=25, blank=True, null=True, verbose_name="Observation Well Status")
    ems = models.CharField(max_length=10, blank=True, null=True, verbose_name="Environmental Monitoring System (EMS) ID")

    utm_zone_code = models.CharField(max_length=10, blank=True, null=True, verbose_name="Zone")
    utm_northing = models.IntegerField(blank=True, null=True, verbose_name="UTM Northing")
    utm_easting = models.IntegerField(blank=True, null=True, verbose_name="UTM Easting")
    utm_accuracy_code = models.CharField(max_length=10, blank=True, null=True, verbose_name="Location Accuracy Code")
    bcgs_id = models.ForeignKey(BCGS_Numbers, db_column='bcgs_id', on_delete=models.CASCADE, blank=True, null=True, verbose_name="BCGS Mapsheet Number")

    decommission_reason = models.CharField(max_length=250, blank=True, null=True, verbose_name="Reason for Decommission")
    decommission_method = models.ForeignKey(DecommissionMethod, db_column='decommission_method_guid', blank=True, null="True", verbose_name="Method of Decommission")
    sealant_material = models.CharField(max_length=100, blank=True, null=True, verbose_name="Sealant Material")
    backfill_material = models.CharField(max_length=100, blank=True, null=True, verbose_name="Backfill Material")
    decommission_details = models.CharField(max_length=250, blank=True, null=True, verbose_name="Decommission Details")

    tracker = FieldTracker()

    class Meta:
        db_table = 'gwells_well'

    def __str__(self):
        if self.well_tag_number:
            return '%d %s' % (self.well_tag_number, self.street_address)
        else:
github lehins / django-wepay / django_wepay / migrations / 0001_initial.py View on Github external
('deleted', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('user_id', self.gf('django.db.models.fields.IntegerField')(primary_key=True)),
            ('access_token', self.gf('django.db.models.fields.CharField')(max_length=127)),
            ('user_name', self.gf('django.db.models.fields.CharField')(max_length=61)),
            ('email', self.gf('django.db.models.fields.EmailField')(max_length=75)),
            ('state', self.gf('django.db.models.fields.CharField')(max_length=15)),
            ('expires', self.gf('django.db.models.fields.IntegerField')(null=True)),
        ))
        db.send_create_signal(u'django_wepay', ['WPUser'])

        # Adding M2M table for field owners on 'WPUser'
        m2m_table_name = db.shorten_name('django_wepay_user_owners')
        db.create_table(m2m_table_name, (
            ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
            ('wpuser', models.ForeignKey(orm[u'django_wepay.wpuser'], null=False)),
            ('user', models.ForeignKey(orm[u'accounts.user'], null=False))
        ))
        db.create_unique(m2m_table_name, ['wpuser_id', 'user_id'])

        # Adding model 'WPAccount'
        db.create_table('django_wepay_account', (
            ('create_datetime', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, null=True, blank=True)),
            ('deleted', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('account_id', self.gf('django.db.models.fields.IntegerField')(primary_key=True)),
            ('name', self.gf('django.db.models.fields.CharField')(max_length=127)),
            ('description', self.gf('django.db.models.fields.CharField')(max_length=2047, blank=True)),
            ('account_uri', self.gf('django.db.models.fields.URLField')(max_length=200)),
            ('payment_limit', self.gf('django_wepay.models_base.MoneyField')(null=True, max_digits=11, decimal_places=2)),
            ('verification_state', self.gf('django.db.models.fields.CharField')(max_length=15)),
            ('type', self.gf('django.db.models.fields.CharField')(max_length=15)),
            ('pending_balance', self.gf('django_wepay.models_base.MoneyField')(default=0, max_digits=11, decimal_places=2)),
            ('available_balance', self.gf('django_wepay.models_base.MoneyField')(default=0, max_digits=11, decimal_places=2)),
github HyOsori / Osori-Website / osoriweb / website / board / models.py View on Github external
# Create your models here.

class InfoArticle(models.Model):
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(
            default=timezone.now)
    view_count = models.IntegerField(default = 0)

    def __str__(self):
        return self.title

class ArticleLikes(models.Model):
	user = models.ForeignKey('auth.User')
	article = models.ForeignKey('board.InfoArticle', related_name='likes')
	created_date = models.DateTimeField(default = timezone.now)
github SEED-platform / seed / seed / models / deprecate.py View on Github external
"""Manager to add useful model filtering methods"""

    def get_queryset(self):
        """Return only active CanonicalBuilding rows."""
        return super(CanonicalManager, self).get_queryset().filter(
            active=True
        )


class CanonicalBuilding(models.Model):
    """
    One Table to rule them all, One Table to find them, One Table to bring
    them all and in the database bind them.
    """

    canonical_snapshot = models.ForeignKey(
        "BuildingSnapshot", blank=True, null=True, on_delete=models.SET_NULL
    )
    active = models.BooleanField(default=True)
    # Django API: relation to AuditLogs GFK, e.g. canon.audit_logs.all()
    audit_logs = GenericRelation(AuditLog)

    objects = CanonicalManager()
    raw_objects = models.Manager()

    labels = models.ManyToManyField('StatusLabel')

    # ManyToManyField(StatusLabel)

    def __str__(self):
        snapshot_pk = 'None'
        if self.canonical_snapshot:
github EuroPython / epcon / conference / models.py View on Github external
ordering = ['name']

    def save(self, **kw):
        if not self.pk:
            try:
                c = ConferenceTag.objects.get(name__iexact=self.name)
            except ConferenceTag.DoesNotExist:
                pass
            else:
                self.pk = c.pk
                return
        return super(ConferenceTag, self).save(**kw)


class ConferenceTaggedItem(GenericTaggedItemBase, ItemBase):
    tag = models.ForeignKey(
        ConferenceTag,
        related_name="%(app_label)s_%(class)s_items",
        on_delete=models.CASCADE,
    )

    class Meta:
        verbose_name = _("Tagged Item")
        verbose_name_plural = _("Tagged Items")


class ConferenceManager(models.Manager):
    def current(self):
        data = cache.get(CURRENT_CONFERENCE_CACHE_KEY)
        a_week = 60 * 60 * 24 * 7

        if data is None:
github hoelsner / product-database / app / productdb / models.py View on Github external
def __str__(self):
        return "User Profile for %s" % self.user.username


class ProductCheckInputChunks(models.Model):
    """chunks for the input product IDs field in the product check"""
    sequence = models.PositiveIntegerField()

    input_product_ids_chunk = models.CharField(
        max_length=65536,
        null=False,
        blank=True
    )

    product_check = models.ForeignKey("ProductCheck")

    class Meta:
        ordering = ['sequence']


class ProductCheck(models.Model):
    name = models.CharField(
        verbose_name="Name",
        help_text="Name to identify the Product Check",
        max_length=256
    )

    migration_source = models.ForeignKey(
        ProductMigrationSource,
        verbose_name="migration source",
        help_text="migration source to identify the replacement options, if not selected the preferred migration path "
github nadineproject / nadine / arpwatch / models.py View on Github external
local_time = localtime(arp_log.runtime)
            key = local_time.date()
            if key in device_logs:
                start = device_logs[key].start
                end = arp_log.runtime
                device_logs[key] = DeviceLog(start, end, end - start)
            else:
                # Create a new device log
                start = end = arp_log.runtime
                device_logs[key] = DeviceLog(start, end, 0)
        return list(device_logs.values())


class ArpLog(models.Model):
    runtime = models.DateTimeField(blank=False, db_index=True)
    device = models.ForeignKey(UserDevice, null=False, on_delete=models.CASCADE)
    ip_address = models.GenericIPAddressField(blank=False, null=False, db_index=True)

    objects = ArpLog_Manager()

    class Meta:
        ordering = ['-runtime']
        get_latest_by = 'runtime'

    def __str__(self):
        return '%s: %s = %s' % (self.runtime, self.ip_address, self.device.mac_address)


class ImportLog(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    file_name = models.CharField(max_length=32, blank=False, null=False, db_index=True)
    success = models.BooleanField(default=False)
github jongman / algospot / www / wiki / models.py View on Github external
# -*- coding: utf-8 -*-
from django.db import models
from django.core.urlresolvers import reverse
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from newsfeed import publish

class PageRevision(models.Model):
    """Stores a specific revision of the page."""
    text = models.TextField()
    edit_summary = models.TextField(max_length=100, blank=True, null=True)
    user = models.ForeignKey(User, null=False)
    created_on = models.DateTimeField(auto_now_add=True)
    revision_for = models.ForeignKey('Page')

    def __unicode__(self):
        return self.revision_for.title + " " + unicode(self.created_on)

class Page(models.Model):
    """Stores a wiki page."""
    title = models.CharField(unique=True, max_length=100)
    slug = models.SlugField(unique=True, max_length=100)
    created_on = models.DateTimeField(auto_now_add=True)
    modified_on = models.DateTimeField(auto_now=True)
    current_revision = models.ForeignKey(PageRevision, related_name='main',
                                         blank=True, null=True)

    def __unicode__(self):
        return self.title
github catmaid / CATMAID / django / applications / catmaid / models.py View on Github external
edition_time = models.DateTimeField(default=datetime.now)
    project = models.ForeignKey(Project)
    # Now new columns:
    relation = models.ForeignKey(Relation)

class ClassInstanceClassInstance(models.Model):
    class Meta:
        db_table = "class_instance_class_instance"
    # Repeat the columns inherited from 'relation_instance'
    user = models.ForeignKey(User)
    creation_time = models.DateTimeField(default=datetime.now)
    edition_time = models.DateTimeField(default=datetime.now)
    project = models.ForeignKey(Project)
    relation = models.ForeignKey(Relation)
    # Now new columns:
    class_instance_a = models.ForeignKey(ClassInstance,
                                         related_name='cici_via_a',
                                         db_column='class_instance_a')
    class_instance_b = models.ForeignKey(ClassInstance,
                                         related_name='cici_via_b',
                                         db_column='class_instance_b')

class BrokenSlice(models.Model):
    class Meta:
        db_table = "broken_slice"
    stack = models.ForeignKey(Stack)
    index = models.IntegerField()

class ClassClass(models.Model):
    class Meta:
        db_table = "class_class"
    # Repeat the columns inherited from 'relation_instance'